wait():让当前线程进入等待状态,同时,wait()也会让当前线程释放它所持有的锁。“直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法”,当前线程被唤醒(进入“就绪状态”)
notify()和notifyAll():则是唤醒当前对象上的等待线程;notify()是唤醒单个线程,而notifyAll()是唤醒所有的线程。
wait(long timeout): 让当前线程处于“等待(阻塞)状态”,“直到其他线程调用此对象的notify()方法或 notifyAll() 方法,或者超过指定的时间量”,当前线程被唤醒(进入“就绪状态”)
wait和notify实现线程间通信:
资源类:
public class Text {
//内容
public String content;
//读写标记:true,可以读,false,可以写
public boolean flag;
//数字
public int num;
}
读数据线程类:
public class ReadThread extends Thread {
private Text text;
public ReadThread(Text text) {
this.text = text;
}
@SneakyThrows
@Override
public void run() {
while (true) {
synchronized (text) {
if (text.flag) {
Thread.sleep(2000);
System.out.println("读到的内容为:" + text.content);
text.flag = false;
System.out.println("=============读取内容结束=============");
text.notify();
}else{
text.wait();
}
}
}
}
}
写入线程实现类:
public class WriteThread extends Thread {
private Text text;
public WriteThread(Text text) {
this.text = text;
}
@SneakyThrows
@Override
public void run() {
while (true) {
synchronized (text) {
if (!text.flag) {
Thread.sleep(2000);
String name = "";
if (text.num % 2 == 0) {
name = "小则";
} else {
name = "小明";
}
text.num = text.num + 1;
text.content = name;
text.flag = true;
System.out.println("-------写入内容结束---------");
text.notify();
} else {
text.wait();
}
}
}
}
}
线程启动类:
public static void main(String[] args) throws InterruptedException {
Text text = new Text();
ReadThread readThread = new ReadThread(text);
WriteThread writeThread = new WriteThread(text);
writeThread.start();
Thread.sleep(1000);
readThread.start();
}