首页 > Linux操作系统 > Linux操作系统 > Java:线程-生产者消费者问题
最近学习java基础知识,到线程的部分,学习了下生产者消费者问题的代码,主要借鉴了网上的代码。。如下:
public class ProducerConsumer {
public static void main(String[] args) {
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);
Consumer c = new Consumer(ss);
new Thread(p).start();
new Thread(c).start();
}
}
//生产者:馒头
class WoTou{
int id;
WoTou(int id){
this.id = id;
}
//消费者查看取出哪个数据,可以重写toString()方法
public String toString(){
return "WoTou:"+id;
}
}
//存放馒头的篮子,使用栈来模拟
class SyncStack{
int index = 0;
WoTou[] arrWT = new WoTou[6];
//往栈里面放数据,如放馒头,出现的问题:放入数据后,没有计数,出现数据丢失问题,所以使用Synchronized
public synchronized void push(WoTou wt){
//如果篮子满了,应该如何处理?应该等待,object的一个方法,wait()
if(index == arrWT.length){
// while(index == arrWT.length){//隐藏的问题2,使用if()不会再检查,所以使用while()
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//锁定在当前对象的线程wait
//隐藏的问题1,notify()没有写的时候,线程就会死锁
this.notify();//也是object的一个方法,wait()方法和notify()方法一起使用,叫醒wait()的线程
}
arrWT[index] = wt;
index++;
}
//从栈里取数据,取出最后放进去的数据,如拿出馒头
public synchronized WoTou pop(){
if(index == 0){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.notify();
}
index--;
return arrWT[index];
}
}
//生产者,来生产馒头,往哪个篮子里面扔?
class Producer implements Runnable{
SyncStack ss = null;
Producer(SyncStack ss){
this.ss = ss;
}
public void run(){
for(int i = 0; i< 20; i++){
WoTou wt = new WoTou(i);
ss.push(wt);
System.out.println(Thread.currentThread().getName()+"生产:"+wt);
try {
Thread.sleep(1000);
// Thread.sleep((int)(Math.random()*1000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//消费者,来消费馒头,从篮子里面取?
class Consumer implements Runnable{
SyncStack ss = null;
Consumer(SyncStack ss){
this.ss = ss;
}
public void run(){
for(int i = 0; i< 20; i++){
WoTou wt = ss.pop();
try {
Thread.sleep(1000);
// Thread.sleep((int)(Math.random()*1000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"消费:"+wt);
}
}
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29056818/viewspace-768244/ ,如需转载,请注明出处,否则将追究法律责任。