public class ThreadCommunicated {
public static void main(String[] args) {
final Printer p = new Printer();
new Thread() {
public void run() {
while (true) {
try {
p.print1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
// -----------------------------------------
new Thread() {
public void run() {
while (true) {
try {
p.print2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
//调用obj的wait(), notify()方法前,必须获得obj锁
//调用obj.wait()后,线程A就释放了obj的锁,否则线程B无法获得obj锁,、
//如果A1,A2,A3都在obj.wait(),则B调用obj.notify()只能唤醒A1,A2,A3中的一个(具体哪一个由JVM决定)。
class Printer {
private int flag = 1;
public void print1() throws InterruptedException {
//第0步:竞争锁,拿到锁的线程才能执行synchronized里面的语句块。没有拿到锁的线程在等待。
synchronized (this) {
//System.out.println("----print1---");
if (flag == 1) // 第一步: 1 ==1 true 第七步:肯定拿到了锁
this.wait(); //第二步 : 线程等待,不往下执行了,并释放锁
System.out.print("天");
System.out.print("津");
System.out.print("滨");
System.out.print("海");
System.out.print("新");
System.out.print("区\n");
flag = 1;
this.notifyAll();
}
}
public void print2() throws InterruptedException {
第0步:竞争锁,拿到锁的线程才能执行synchronized里面的语句块。没有拿到锁的线程在等待。
synchronized (this) { //第三步: 拿到了锁 ,继续执行。
if (flag == 2) //第四步: 1 == 2 --> false,跳过等待。
this.wait();
System.out.print("北");
System.out.print("京");
System.out.print("颐");
System.out.print("和");
System.out.print("园\n");
flag = 2;
this.notifyAll(); //第五步:唤醒刚才等待的全部线程
}//退出synchronized块,释放锁, 第六步: 锁竞争.jvm随机分配给线程的锁,重复第0步
}
}
最简单了理解线程通信的举例
最新推荐文章于 2022-01-19 14:28:28 发布