wait与notify线程之间的通信
1.wait与notify是使用在同步代码块或同步方法中的
2.他们都是Object的方法
3.notify是需要获取锁的,会随机唤醒一个处理等待状态的线程
4.wait方法是会释放锁的
5.notifyAll会唤醒所有wait的线程,但是拿到cup时间片的线程只有一个
6.Thread类的一个方法join()
B线程在A线程中调用join()方法,那么A线程会等待B线程的执行完毕,A线程才继续往下执行
package com.roy.condition;
/**
* @Authror royLuo
* @Date 2020/2/29 14:59
**/
public class WaitAndNotifyDemo {
//定义信号量
private int signal;
public synchronized void a(){
while (signal!=0){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
signal++;
System.out.println("a");
notifyAll();
}
public synchronized void b(){
while (signal!=1){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
signal++;
System.out.println("b");
notifyAll();
}
public synchronized void c(){
while (signal!=2){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("c");
signal = 0 ;
notifyAll();
}
public static void main(String[] args) {
WaitAndNotifyDemo demo = new WaitAndNotifyDemo();
new Thread(new E(demo)).start();
new Thread(new F(demo)).start();
new Thread(new G(demo)).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行完毕");
}
}
class E implements Runnable{
private WaitAndNotifyDemo demo;
public E(WaitAndNotifyDemo demo){
this.demo =demo;
}
@Override
public void run() {
while (true)
demo.a();
}
}
class F implements Runnable{
private WaitAndNotifyDemo demo;
public F(WaitAndNotifyDemo demo){
this.demo =demo;
}
@Override
public void run() {
while (true)
demo.b();
}
}
class G implements Runnable{
private WaitAndNotifyDemo demo;
public G(WaitAndNotifyDemo demo){
this.demo =demo;
}
@Override
public void run() {
while (true)
demo.c();
}
}
DCD