java进程等待唤醒机制
等待唤醒机制是建立线程安全的基础之上设置的
举例:通过设置线程(生产者)和获取线程(消费者)针对同一个学生对象进行操作
Student类

生产者线程
public class ProductThread extends Thread{
private Student s;
private int i = 0;
public ProductThread(Student s) {
this.s = s;
}
@Override
public void run() {
while (true){
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (s){ //同步代码块
//应该先看一看数据有没有被消费,若被消费了,才赋新的值,通知消费者消费,若没有消费,等待消费者消费
if(s.getFlag()){
//若学生对象中flag成员变量值是true,生产者就不会生产
//由多个线程共享且唯一的锁对象进行等待
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(i%2==0){
s.setName("Bob");
s.setAge(19);
}else {
s.setName("Alice");
s.setAge(18);
}
i++;
s.setFlag(true);
//赋值之后应该通知消费者进行消费数据
s.notify();
}
}
}
}
消费者线程
package com.shujia.day19.waitDemo;
public class ConsumerThread extends Thread {
private Student s;
public ConsumerThread(Student s) {
this.s = s;
}
@Override
public void run() {
// Student s = new Student();
while (true) {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (s) {
//消费者消费数据之前,先判断数据有没有生产,若生产了,就取值打印,若没有生产,就等待,通知生产者生产
if (!s.getFlag()) {
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(s.getName() + "-" + s.getAge());
s.setFlag(false);
//通知生产者赋值新的数据
s.notify();
}
}
}
}
测试类
public class StudentDemo {
public static void main(String[] args) {
Student s = new Student();
ProductThread p1 = new ProductThread(s);
ConsumerThread c1 = new ConsumerThread(s);
p1.start();
c1.start();
}
}


浙公网安备 33010602011771号