java实现生产者消费者,笔试遇到过
/*
生产者消费者模型, 也就是, 说在这里用java来直接模拟生产者与消费者, 生产一个取出一个, 取出一个再生产一个
用Mes对象, 来存储生产和取出的消息, 用生产者和消费者两个线程来表示生产和取出的过程, 用synchronized来保证数据的同步
*/
class Mes{
private String name; //信息组成内容, 姓名
private String des; //信息组成内容, 描述private boolean flag = true; //用于表示目前所处状态, 如果, flag为true, 则表示可以生产, 而不可以消费, 反过来则, 生产线程等待, 消费线程可以执行
public synchronized void set(String name, String des) //生产消息的代码
{if(!flag) //如果不能生产则挂掉, 也就是让县城等待 { try { super.wait(); } catch (InterruptedException e) { e.printStackTrace(); } ; } try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }
//如果可以生产:
this.name = name;
this.des = des;
//这个时候, 改变目前所处的状态:
flag = false;
//唤醒消费线程:
super.notify();
}
public synchronized String get() //取出消息的代码
{
if(flag) //如果处于不能取出的状态, 则:
{
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//将数据取出之后, 记得唤醒生产线程
try{
return this.name + "-" + this.des;
}finally {
super.notify();
flag = true; //改变线程目前所处的状态
}
}}
class coms implements Runnable{ //消费者类
private Mes mes;
public coms(Mes mes)
{
this.mes = mes;
}
@Override
public void run() {
for(int x =0; x< 50; x++)
{
System.out.println(this.mes.get());
}
}}
class producer implements Runnable{ //生产者类
private Mes mes;
public producer(Mes mes)
{
this.mes = mes;
}
@Override
public void run() {
for(int x=0; x<50; x++)
{
if(x%2 == 0)
{
mes.set("Winni", "真是一个漂亮的小姑娘");
}
else
{
mes.set("小花小花", "blingblingbling");
}
}
}}
public class ProducerAndConsumer {
public static void main(String [] args)
{
System.out.println("咋回事儿");
Mes mes = new Mes();
// con c = new con(mes);
coms cc = new coms(mes);
producer p = new producer(mes);
new Thread(p).start();
new Thread(cc).start();
}}
查看17道真题和解析