/**
* 生产者消费者 wait() notify()
*/
public class Demo1 {
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 {
List list;
public Producer(List list){
this.list = list;
}
@Override
public void run() {
while (true) {
synchronized(list){
System.out.println(Thread.currentThread().getName() +" =>执行");
if (list.size() > 0) {
try {
System.out.println(Thread.currentThread().getName() +"生产满了,等待");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Object object = new Object();
list.add(object);
System.out.println(Thread.currentThread().getName() + " -----> 产生" + list.size() + "个");
list.notify();
}
}
}
}
//消费者
class Consumer implements Runnable {
List list;
public Consumer(List list) {
this.list = list;
}
@Override
public void run() {
while (true) {
synchronized(list){
System.out.println(Thread.currentThread().getName() +" =>执行");
if (list.size() == 0) {
try {
System.out.println(Thread.currentThread().getName() +" =>无产品,等待");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.remove(0);
System.out.println(Thread.currentThread().getName() + " -----> 消费" + (list.size()+1) + "个");
list.notify();
}
}
}
}
多线程——生产者消费者代码
最新推荐文章于 2023-07-21 15:38:34 发布