package thread;
/**
* 生产者消费者模式
* @author 编程只服JAVA
*
*/
public class ProducerConsumer {
public static void main(String[] args) {
SyncStack ss=new SyncStack();
Producer producer=new Producer(ss);
Consumer consumer=new Consumer(ss);
Thread t1=new Thread(producer);
Thread t2=new Thread(consumer);
t1.start();
t2.start();
}
}
/**
* 窝头类:一个篮子里面的馒头
*/
class WoTou{
int id;//给每一个窝头标记一个id
WoTou(int id){
this.id=id;
}
public String toString(){
return "WoTou:"+id;
}
}
/**
* 利用栈来模拟存放窝头的篮子
*/
class SyncStack{
int index=0;
WoTou[] arrWT=new WoTou[6];//可以装6个窝头
//放窝头:锁住该方法,防止多线程访问,造成前后结果不一致
public synchronized void push(WoTou wt){
if (index==arrWT.length) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notify();//如果有多个线程 改为notifyAll即可
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];
}
}
/**
* 生产者:相当一个线程,继承Runnable接口
*/
class Producer implements Runnable{
SyncStack ss=null;
public Producer(SyncStack ss) {
this.ss=ss;
}
public void run() {
for(int i=1;i<=20;i++){
WoTou wt=new WoTou(i);
ss.push(wt);
System.out.println("生产了:"+wt);
try {
Thread.sleep((int)Math.random()*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
SyncStack ss=null;
public Consumer(SyncStack ss) {
this.ss=ss;
}
public void run() {
for(int i=1;i<=20;i++){
WoTou wt=ss.pop();
System.out.println("消费了:"+wt);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
描述消费者和生产者模式的代码(有些公司面试的时候会让你直接写一段代码)
最新推荐文章于 2021-05-12 12:47:55 发布