Java线程的同步演示代码,java线程演示,package Wint
分享于 点击 36251 次 点评:20
Java线程的同步演示代码,java线程演示,package Wint
package Winter;class Buffer2{ private int value; private boolean isEmpty=true;//value是否为空的信号量 synchronized void put(int i)//放数据 { while(!isEmpty) { try{ this.wait(); }catch(InterruptedException e) { System.out.println(e.getMessage()); } } value=i; isEmpty=false; notify(); } synchronized int get(){//取数据 while(isEmpty){ try{ this.wait(); }catch(InterruptedException e){System.out.println(e.getMessage());} } isEmpty=true; notify(); return value; }}class Get2 extends Thread{//取数据线程 private Buffer2 bf; public Get2(Buffer2 bf){this.bf=bf;} public void run() { for(int i=1;i<6;++i) System.out.println("\t\t Get2 get:" +bf.get()); }}public class Put2 extends Thread {//放数据线程 /** * @param args */ private Buffer2 bf; public Put2(Buffer2 bf){this.bf=bf;} public void run() { for(int i=1;i<6;++i) { bf.put(i); System.out.println("put2 put:"+i); } } public static void main(String[] args) { // TODO Auto-generated method stub Buffer2 bf=new Buffer2(); (new Put2(bf)).start(); (new Get2(bf)).start(); }}
wait()方法是当前线程变为阻塞状态,并主动释放互斥锁,这一点和sleep方法不同的地方,sleep方法不会释放互斥锁。
notify()唤醒等待队列的其他线程继续执行,是这些线程变成可运行状态。notifyAll()唤醒等待队列中的全部线程继续执行。
用户点评