1.线程通信,直接看代码吧。
public class Test3 {
public static void main(String[] args) {
phen p= new phen ();
new Thread(()->{
for (int i = 0; i <10 ; i++) {
p.production ();
}
},"a").start();
new Thread(()->{
for (int i = 0; i <10 ; i++) {
p.consume ();
}
},"B").start();
}
}
class phen{
private boolean flage = false;
//消费
public synchronized void consume () {
while (flage == false) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("这个线程在消费东西");
flage = false;
this.notify();
}
//生产者
public synchronized void production () {
while (flage == true) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("这个线程在生产东西");
flage = true;
this.notify();
}
}