import java.util.ArrayList;
import java.util.List;
/*
生产者和消费者模式:
生产者负责生产,消费者负责消费。线程要达到均衡。
wait和notify方法是普通java对象都有的方法。
o.wait() 让o对象上的线程进入等待状态,释放掉线程之前占有的o对象的锁。
o.notify() 唤醒正在o对象上等待的线程,不会释放o对象之前占有的锁。
模拟需求:
仓库采用List集合,假设只能存储1个对象。做到生产1个消费1个,
*/
public class WaitTest {
public static void main(String[] args) {
// 创建一个共享的仓库对象
List list = new ArrayList();
Thread t1 = new Thread(new Producer(list));
Thread t2 = new Thread(new Consumer(list));
t1.setName("生产者线程");
t2.setName("消费者线程");
t1.start();
t2.start();
}
}
class Producer implements Runnable {
private List list;
public Producer(List list) {
this.list = list;
}
@Override
public void run() {
// 使用死循环模拟一直生产
while (true) {
// 给仓库对象list加锁
synchronized (list) {
if (list.size() > 0) {
try {
// 当前线程进入等待状态,释放Producer之前占有的list集合的锁
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 程序到这里说明仓库是空的,需要生产
Object obj = new Object();
list.add(obj);
System.out.println(Thread.currentThread().getName() + "--->" + obj);
// 唤醒进行消费
list.notify();
}
}
}
}
class Consumer implements Runnable {
private List list;
public Consumer(List list) {
this.list = list;
}
@Override
public void run() {
// 使用死循环模拟一直消费
while (true) {
// 给仓库对象list加锁
synchronized (list) {
if (list.size() == 0) {
try {
// 当前线程进入等待状态,释放Producer之前占有的list集合的锁
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 程序到这里说明仓库是满的,需要消费
Object obj = list.remove(0);
System.out.println(Thread.currentThread().getName() + "--->" + obj);
// 唤醒进行生产
list.notify();
}
}
}
}
javase:线程wait
最新推荐文章于 2024-07-29 14:22:26 发布