【java多线程】 生产者消费者问题 代码

问题描述:保持多线程同步 生产一个消费一个

 class Message{
	private String title;
	private String content;
	private boolean flag=true;//表示生产或者消费
	//flag =true 允许生产,但是不允许消费
	//flag =false 允许消费 不允许生产
 public synchronized void set(String title,String content) {
	 if(this.flag==false) {
		 try {
			super.wait();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	 }
	 this.title=title;
	 try {
		Thread.sleep(100);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	 this.content=content;
	 this.flag=false;//已经生产完毕了
	 super.notify();//唤醒等待的线程
 }
 public synchronized String get() {
	 if(flag==true) {
		 try {
			super.wait();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	 }
	 try {
		Thread.sleep(100);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}try {
	 return this.title+"-"+this.content;
	}finally {
		this.flag=true;
		super.notify();
	}
 }
}

class Producer implements Runnable{
private Message msg;
public Producer(Message msg) {
	this.msg=msg;
	
}@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int x=0;x<100;x++) {
			if(x%2==0) {
				this.msg.set("王健","宇宙大帅哥");
				 
				 
			}else {
				this.msg.set("赵高","第一人");
			}
		}
	}
	
}

class Consumer implements Runnable{
	private Message msg;
	public Consumer(Message msg) {
		this.msg=msg;
	}
	@Override
	public void run() {
	 for(int x=0;x<100;x++) {
		 try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 System.out.println(this.msg.get());
	 }
		
	}
	
}

 
 
public class Test1 {
	 public static void main(String[] args) throws Exception {
  Message msg=new Message();
  **new Thread(new Producer(msg)).start();//启动生产者线程
  new Thread(new Consumer(msg)).start();//启动消费者线程
		
	}
 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值