wait与notify实现多线程的协调通信

来源:互联网 发布:知客文化传播 培训 编辑:程序博客网 时间:2024/06/01 22:08
public class Sample{public static void main(String args[]){SampleTest sampletest=new SampleTest();IncreaseThread it=new IncreaseThread(sampletest);DecreaseThread dt=new DecreaseThread(sampletest);it.start();dt.start();}}class SampleTest{private int number;public synchronized void increase(){while(number!=0){try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}number++;System.out.println(number);this.notify();}public synchronized void decrease(){while(number==0){try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}number--;System.out.println(number);this.notify();}}class IncreaseThread extends Thread{private SampleTest sampletest;public IncreaseThread(SampleTest sampletest){this.sampletest=sampletest;}@Overridepublic void run(){// TODO Auto-generated method stubfor(int i=0;i<20;i++){try {Thread.sleep((long)(Math.random()*1000));} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}sampletest.increase();}}}class DecreaseThread extends Thread{private SampleTest sampletest;public DecreaseThread(SampleTest sampletest){this.sampletest=sampletest;}@Overridepublic void run(){// TODO Auto-generated method stubfor(int i=0;i<20;i++){try {Thread.sleep((long)(Math.random()*1000));} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}sampletest.decrease();}}}

0 0
原创粉丝点击