java 通过使用wait和notify进行线程之间通信(代码)

来源:互联网 发布:java 微信语音聊天 编辑:程序博客网 时间:2024/06/05 16:46
public class Test {    private final Operate operate = new Operate();        public static void main(String[] args) {            new Thread(new Runnable() {            @Override            public void run() {                for (int i = 1; i <= 50; i++) {                    operate.doSubMethod(i);                }            }        }).start();        for (int i = 1; i <= 50; i++) {            operate.doSupMethod(i);        }    }}class Operate{    private boolean isSub = true;        public synchronized void doSubMethod(int i){        while(!isSub){            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        for (int j = 1; j <= 12; j++) {            System.out.println("Sub--> " + Thread.currentThread().getName() + "\tloop:" + i + "\t第" + j + "次");        }        isSub = false;        notify();    }       public synchronized void doSupMethod(int i){        while(isSub){            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        for (int j = 1; j <= 88; j++) {            System.out.println("Sup--> " + Thread.currentThread().getName() + "\tloop:" + i + "\t第" + j + "次");        }        isSub = true;        notify();    }}



0 0
原创粉丝点击