Java线程通信在使用的时候需要我们不断学习,在学习的时候会有很多的问题存在。其实我们在源代码中就能发现其中的奥秘。因为ThreadNum和ThreadChar都有对Objecto的引用,所以你wait和notify的时候都应该同步,Java线程通信具体看如下:
- public class Test8 {
- public static void main(String[] args){
- Object o=new Object();
- Thread n=new ThreadNum(o);
- Thread c=new ThreadChar(o);
- n.start();
- c.start();
- }
- }
- class ThreadNum extends Thread{
- Object o;
- public ThreadNum(Object o){
- this.o=o;
- }
- public void run(){
- for(int i=1;i<26;i++){
- System.out.println(i);
- System.out.println(++i);
- try {
- synchronized (this) {
- this.wait();
- }
- } catch (InterruptedException e) {}
- synchronized (this) {
- this.notify();
- }
- }
- }
- }
- class ThreadChar extends Thread{
- Object o;
- public ThreadChar(Object o){
- this.o=o;
- }
- public void run(){
- for(char a='A';a<='Z';a++){
- System.out.println(a);
- synchronized (this) {
- this.notify();
- }
- try {
- synchronized (this) {
- this.wait();
- }
- } catch (InterruptedException e) {}
- }
- }
- }
以上就是对Java线程通信的详细介绍。
新闻名称:Java线程通信源代码中的奥秘探究
文章URL:http://www.csdahua.cn/qtweb/news34/418534.html
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网