JAVA 多线程 线程间的通讯

来源:互联网 发布:在线报价系统源码 编辑:程序博客网 时间:2024/04/29 06:44
  1.    编程间通讯: 
  2.     其实就是多个线程在操作同一个资源 
  3.     但是操作的动作不同 
  4.  
  5.  
  6. wait(); 
  7. notify(); 
  8. notifyAll(); 
  9.  
  10. 都使用在同步中,因为要对持有的监视器(锁)的线程操作 
  11. 所以要使用在同步中,因为只有同步才具有锁 
  12.  
  13. 将这些操作线程的方法定义在Object类中的原因是因为这些方法在操作同步线程时, 
  14. 都需要标示他们所操作线程持有的锁 
  15. 只有同一个锁上的被等待线程,可以被同一个锁上的notify唤醒 
  16. 不可以对不同锁中的线程进行唤醒 
  17.  
  18. 也就是说 等待和唤醒必须是同一个锁 
  19.  
  20. 而锁也可以是任意对象,所以可以被任意对象调用的方法定义在Object类中 
  21.  
  22.  
  23. */  
  24.   
  25. class Res  
  26. {  
  27.     private String name;  
  28.     private String sex;  
  29.     private boolean flag = false;  
  30.       
  31.     public synchronized void set(String name, String sex)  
  32.     {  
  33.         if(flag)  
  34.             try{this.wait();}catch(Exception e){}  
  35.         this.name = name;  
  36.         this.sex = sex;  
  37.   
  38.         flag = true;  
  39.         this.notify();  
  40.     }  
  41.   
  42.     public synchronized void out()  
  43.     {  
  44.         if(!flag)  
  45.         try{this.wait();}catch(Exception e){}  
  46.         System.out.println(this.name +"----"this.sex);  
  47.       
  48.         flag = false;  
  49.         this.notify();  
  50.     }  
  51. }  
  52.   
  53. class Input implements Runnable  
  54. {  
  55.     private Res r;  
  56.     Input(Res r)  
  57.     {  
  58.         this.r = r;  
  59.     }  
  60.   
  61.     public void run()  
  62.     {  
  63.         int x = 0;  
  64.         while(true)  
  65.         {  
  66.             if(x == 0)  
  67.                 r.set("zhangshan","man");  
  68.             else  
  69.                 r.set("李四","男");  
  70.           
  71.         x = (x+1)%2;                  
  72.         }  
  73.     }     
  74. }  
  75.   
  76. class Output implements Runnable  
  77. {  
  78.     private Res r;  
  79.     Output(Res r)  
  80.     {  
  81.         this.r = r;  
  82.     }  
  83.   
  84.     public void run()  
  85.     {  
  86.         while(true)  
  87.         {  
  88.             synchronized(r)  
  89.             {  
  90.                 r.out();  
  91.             }  
  92.         }   
  93.     }  
  94. }  
  95.   
  96. class TestDemo  
  97. {  
  98.     public static void main(String []args)  
  99.     {  
  100.         Res r = new Res();  
  101.   
  102.         new Thread(new Input(r)).start();  
  103.         new Thread(new Output(r)).start();  
  104. /*      Input in = new Input(r); 
  105.         Output out = new Output(r); 
  106.  
  107.         Thread t1 = new Thread(in); 
  108.         Thread t2 = new Thread(out); 
  109.  
  110.         t1.start(); 
  111.         t2.start(); 
  112. */  
  113.   
  114.     }  
  115. }  


0 0
原创粉丝点击