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


  本文标签: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线程通信的详细介绍  。