生产者和消费者
概述
生产者和消费者是在大学java课程中刚开始讲线程的时候的老师讲的一个经典的一个问题,假如一个手工艺人10分钟制作1个手工品,当消费者去进行购买的时候怎么去保证购买成功,当消费者购买完了生产的手工品,还能继续去购买吗?作为生产者的手工艺人又是什么状态?手工艺人制作完手工品之后,消费者又是什么状态?当有100个手工品的时候,怎么去保证多个消费者(多线程)买不到同一个商品。
代码实现
这种实现是使用synchronized 关键字去实现的,对资源进行加锁,生产者还是消费者都会对资源进行判断,例如消费者消费的时候没有资源了执行notify唤醒生产者线程。生产者生产完,使用notifyAll唤醒消费者线程。
public class Demo2 {
public static void main(String[] args) {
List list = new ArrayList();
Thread thread = new Thread(new Productor(list));
Thread thread1 = new Thread(new Consumer(list));
thread.start();
thread1.start();
}
}
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() < 1) {//list中没有元素
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " " + list.remove(0));
list.notify();//唤醒生产者线程
}
}
}
}
class Productor implements Runnable{
private List list;// 生产的公共资源
public Productor(List list){
this.list = list;
}
@Override
public void run() {
while(true){
Random random = new Random();
synchronized(list){
if(list.size() >0 ){
try {
list.wait(); //这个线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add("苹果手机"+random.nextInt(100));
System.out.println(Thread.currentThread().getName()+" "+list.get(0));
list.notifyAll(); //通知消费者
}
}
}
}