一共三个类:Consumer Producer Main
注释都在代码里,不懂的欢迎留言.
消费者
public class Consumer implements Runnable{
List<Integer> cache;
Integer num = 10; //控制次数,否则会无限循环下去无休止.
public Consumer(List<Integer> cache){
this.cache = cache;
}
@Override
public void run() {
while (true){
synchronized (cache){ //synchronized锁定仓库这个对象,为了避免消费的时候其他线程访问仓库造成错误.
try{
while (cache.size() == 0){//仓库为空的情况下,消费者等待
cache.wait();
}
//能走到这一步说明仓库不为空,开始消费了.
System.out.println("消费者消费:"+cache.get( 0 ));
cache.remove( 0 );
cache.notifyAll();
num--;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
生产者
public class Producer implements Runnable {
List<Integer> cache; //用ArrayList替代仓库,大小为1
Integer num = 10; //来控制生产者生产多少次,如果没有这个就会一直不休息的生产.
Random random = new Random( ); //用来随机产生物资.
public Producer(List<Integer> cache){
this.cache = cache;
}
@Override
public void run() {
while (num > 0){
synchronized (cache){
try {
while (cache.size() > 0){
cache.wait(); //当仓库中有东西的时候,停止生产.调用wait方法,将该线程放到cache对象的等待池中.
}
Thread.sleep( 500 ); //可有可无,为了显示出生产消费的变化.
Integer integer = random.nextInt(10);
cache.add( integer ); //随机产生物资并且放在仓库中
System.out.println("生产者生产:"+integer);
cache.notifyAll(); //在cache对象的等待池中唤醒正在等待的消费者线程.
num--;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
主函数
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>( 1 ); //用来当仓库的ArrayList,大小为1
Consumer consumer = new Consumer( list );
Producer producer = new Producer( list );
Thread thread1 = new Thread( consumer ); //消费者线程
Thread thread2 = new Thread( producer ); //生产者线程
thread1.start();
thread2.start();
}
}
注释都在代码里,不懂的欢迎留言.