Java线程通信源代码中的奥秘探究

Java线程通信在使用的时候需要我们不断学习,在学习的时候会有很多的问题存在。其实我们在源代码中就能发现其中的奥秘。因为ThreadNum和ThreadChar都有对Objecto的引用,所以你wait和notify的时候都应该同步,Java线程通信具体看如下:

 
 
 
  1. public class Test8 {  
  2. public static void main(String[] args){   
  3. Object o=new Object();   
  4. Thread n=new ThreadNum(o);   
  5. Thread c=new ThreadChar(o);   
  6. n.start();   
  7. c.start();   
  8. }   
  9. }   
  10. class ThreadNum extends Thread{   
  11. Object o;   
  12. public ThreadNum(Object o){   
  13. this.o=o;   
  14. }   
  15. public void run(){   
  16. for(int i=1;i<26;i++){   
  17. System.out.println(i);   
  18. System.out.println(++i);   
  19. try {   
  20. synchronized (this) {  
  21. this.wait();   
  22. }  
  23. } catch (InterruptedException e) {}   
  24. synchronized (this) {  
  25.  
  26. this.notify();   
  27. }  
  28. }   
  29. }   
  30. }   
  31. class ThreadChar extends Thread{   
  32. Object o;   
  33. public ThreadChar(Object o){   
  34. this.o=o;   
  35. }   
  36. public void run(){   
  37. for(char a='A';a<='Z';a++){   
  38. System.out.println(a);   
  39. synchronized (this) {  
  40.  
  41. this.notify();   
  42. }  
  43. try {   
  44. synchronized (this) {  
  45. this.wait();   
  46. }  
  47. } catch (InterruptedException e) {}   
  48. }   
  49. }   
  50. }  

以上就是对Java线程通信的详细介绍。

新闻名称:Java线程通信源代码中的奥秘探究
文章URL:http://www.csdahua.cn/qtweb/news34/418534.html

网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网