Object类中wait和nitify方法(生产者、消费者模式)
- 1、wait和notify不是线程对象的方法而是java中如何一个对象的方法。两个方法都是Object自带的
- 2、wait的作用
- 让对象上活动的线程进入等待状态,无期限等待,直到被唤醒
- 3、notify的作用
- 唤醒正在对象上等待的线程,notifyAll()唤醒对象上所有等待的对象
public class WaitNotifyTest {
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死循环一直生产
while (true){
//加锁
synchronized (list){
if (list.size()>0){//大于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.notifyAll();
}
}
}
}
class Consumer implements Runnable{
private List list;
public Consumer(List list){
this.list=list;
}
@Override
public void run() {
//
while (true){
synchronized (list){
if(list.size()==0){
try {
//如何集合里面没有元素
//消费者线程进入等待,释放list集合的锁
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果集合中有元素则进行消费
Object obj =list.remove(0);
System.out.println(Thread.currentThread().getName()+"-->"+obj);
//唤醒生产者进行生产
list.notifyAll();
}
}
}
}