1.什么时候需要通信
* 多个线程并发执行时, 在默认情况下CPU是随机切换线程的
* 如果我们希望他们有规律的执行, 就可以使用通信, 例如每个线程执行一次打印
* 2.怎么通信
* 如果希望线程等待, 就调用wait()
* 如果希望唤醒等待的线程, 就调用notify();
* 这两个方法必须在同步代码中执行, 并且使用同步锁对象来调用
public class Demo1_Notify {
public static void main(String[] args) {
// TODO Auto-generated method stub
Printer2 p=new Printer2();
new Thread() {
public void run() {
while(true) {
try {
p.print1();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
new Thread() {
public void run() {
while(true) {
try {
p.print2();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
}
//等待唤醒机制
class Printer2{
private int flag=1;
public void print1() throws InterruptedException {
synchronized(this) {
if(flag!=1) {
this.wait();
}
System.out.println("同步");
System.out.println("代码块");
System.out.println("1");
flag=2;
this.notify();
}
}
public void print2() throws InterruptedException {
synchronized(this) {//对象本身
if(flag!=2) {
this.wait();//当前线程等待
}
System.out.println("同步2");
System.out.println("代码2");
System.out.println("2");
flag=1;
this.notify();//随机唤醒单个等待的线程
}
}
}
输出结果:--二个线程之间轮回输出