线程间通信 wait() notify()

来源:互联网 发布:安装win7无法连接网络 编辑:程序博客网 时间:2024/06/01 08:50

线程间通过锁对象进行同步,将锁加在多个线程共同访问的资源上,实现多个线程的同步

线程间  可以通过 notify(),notifyAll(),wait()方法进行调度,wait()必须用在同步代码块或同步方法里,锁对象调用wait()后,释放同步方法锁,给其他具有同等优先级,或者更高优先级的线程执行,


public class TraditionalThreadCommunication {public static void main(String[] args) {final Bussiness bussiness = new Bussiness();new Thread(new Runnable() {@Overridepublic void run() {for (int m = 0; m < 50; m++) {bussiness.sub(m);}}}).start();for (int m = 0; m < 50; m++) {bussiness.main(m);}}}class Bussiness {private boolean bShouldSub = true;public synchronized void main(int m) {//为什么不用if,而用while//防止伪同步,有时候线程wait()了也自动唤醒会执行,这时while判断,while (!bShouldSub) {try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}for (int i = 0; i < 100; i++) {System.out.println("main thread sequence of" + i+"of loop "+m);}bShouldSub = false;this.notify();}public synchronized void sub(int m) {while (bShouldSub) {try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}for (int i = 0; i < 10; i++) {System.out.println("sub thread sequence of" + i+ "of loop "+m);}bShouldSub = true;this.notify();}}


0 0
原创粉丝点击