/**
* 两个线程,一个+1,一个-1
*
* 知识点:线程间的通信
*/
public class NotifyWaitDemoA {
/*
* 虚假唤醒现象。多线程之间的判断使用while,不用if
*/
public static void main(String[] args) {
ShareDate shareDate = new ShareDate();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
shareDate.increment();
}catch (Exception e) {
e.getStackTrace();
}
}
}, "aa").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
shareDate.increment();
}catch (Exception e) {
e.getStackTrace();
}
}
}, "cc").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
shareDate.decrement();
}catch (Exception e) {
e.getStackTrace();
}
}
}, "bb").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
shareDate.decrement();
}catch (Exception e) {
e.getStackTrace();
}
}
}, "dd").start();
}
public static class ShareDate {
private Integer number = 0;
public synchronized void increment() throws Exception{
// 1、判断
while (number != 0) {
this.wait();
}
// 2、干活
++number;
System.out.println(Thread.currentThread().getName() +":"+ number);
// 3、通知
this.notifyAll();
}
public synchronized void decrement() throws Exception{
// 1、判断
while (number == 0) {
this.wait();
}
// 2、干活
--number;
System.out.println(Thread.currentThread().getName() +":"+ number);
// 3、通知
this.notifyAll();
}
}
}
线程间的通信_A
于 2020-05-06 14:28:41 首次发布