[Java] Java线程的同步演示代码 →→→→→进入此内容的聊天室

来自 , 2020-11-30, 写在 Java, 查看 172 次.
URL http://www.code666.cn/view/7dc3338d
  1. package Winter;
  2.  
  3. class Buffer2{
  4.         private int value;
  5.         private boolean isEmpty=true;//value是否为空的信号量
  6.         synchronized void put(int i)//放数据
  7.         {
  8.                 while(!isEmpty)
  9.                 {
  10.                         try{
  11.                                 this.wait();
  12.                           }catch(InterruptedException e)
  13.                         {
  14.                                 System.out.println(e.getMessage());
  15.                         }
  16.                 }
  17.                 value=i;
  18.                 isEmpty=false;
  19.                 notify();
  20.         }
  21.         synchronized int get(){//取数据
  22.                 while(isEmpty){
  23.                         try{
  24.                                  this.wait();
  25.                         }catch(InterruptedException e){System.out.println(e.getMessage());}
  26.                 }
  27.                 isEmpty=true;
  28.                 notify();
  29.                 return value;
  30.         }
  31.        
  32. }
  33. class Get2 extends Thread{//取数据线程
  34.         private Buffer2 bf;
  35.         public Get2(Buffer2 bf){this.bf=bf;}
  36.         public void run()
  37.         {
  38.                 for(int i=1;i<6;++i)
  39.                         System.out.println("\t\t Get2 get:" +bf.get());
  40.                
  41.         }
  42.        
  43. }
  44. public class Put2 extends Thread {//放数据线程
  45.  
  46.         /**
  47.          * @param args
  48.          */
  49.         private Buffer2 bf;
  50.         public Put2(Buffer2 bf){this.bf=bf;}
  51.         public void run()
  52.         {
  53.                 for(int i=1;i<6;++i)
  54.                 {
  55.                         bf.put(i);
  56.                         System.out.println("put2 put:"+i);
  57.                        
  58.                 }
  59.                
  60.         }
  61.         public static void main(String[] args) {
  62.                 // TODO Auto-generated method stub
  63.         Buffer2 bf=new Buffer2();
  64.         (new Put2(bf)).start();
  65.         (new Get2(bf)).start();
  66.         }
  67.  
  68. }
  69.  
  70. //java/6483

回复 "Java线程的同步演示代码"

这儿你可以回复上面这条便签

captcha