package blockqueen;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class xiaofeizhe {
final BlockingQueue<String> queue=new ArrayBlockingQueue<String>(5);
public static void main(String[] args) {
xiaofeizhe xiaofeizhe=new xiaofeizhe();
xiaofeizhe.begin();
}
public void begin() {
Thread t1=new Thread(new chihuo());
t1.start();
Thread t2=new Thread(new laoban());
t2.start();
}
class laoban implements Runnable{
int count=0;
@Override
public void run() {
while(true)
{
try {
Thread.sleep((long)(Math.random()*1000));
queue.put("馒头"+(++count));
System.out.println("生产一个馒头,总共生产了"+count+"个馒头"+"还有"+queue.size()+"个");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class chihuo implements Runnable{
int count=0;
@Override
public void run() {
while(true)
{
try {
Thread.sleep((long)(Math.random()*1000));
System.out.println("吃一个馒头,总共吃了"+(++count)+"个馒头"+"还有"+queue.size()+"个"+"这是第"+queue.take()+"个馒头");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
本文介绍了一个基于生产者消费者模式的馒头生产线模拟,通过两个线程分别模拟生产者和消费者角色,实现馒头的生产与消费过程。生产者线程随机生成馒头,并将馒头放入阻塞队列中;消费者线程从队列中取出馒头进行消费,并实时更新已消费馒头的数量和队列中的剩余馒头数量。
2415

被折叠的 条评论
为什么被折叠?



