生产电脑---多线程案例

设置一个生产电脑和搬运电脑类,要求生产出一台电脑就搬走一台电脑,如果没有新电脑产出,则搬运等待,如果生产的没有搬走,则要等待电脑搬走之后再生产,并统计地产电脑的电脑数量。

生产者消费者问题

package wzr.thread.test2;

public class ComputerSell {

	public static void main(String[] args) {
		Resource res=new Resource();
		new Thread(new Producer(res)).start();
		new Thread(new Consumer(res)).start();
	}

}
class Producer implements Runnable{
	private Resource resource;
	public Producer(Resource resource) {
		this.resource=resource;
	}
	public void run() {
		for(int x=0;x<50;x++) {
			try {
				resource.make();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
class Consumer implements Runnable{
	private Resource resource;
	public Consumer(Resource resource) {
		this.resource=resource;
	}
	public void run() {
		for(int x=0;x<50;x++) {
			try {
				resource.get();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
class Resource{
	private Computer computer;
	//private boolean flag=true;
	public synchronized void make()throws Exception {
		if(computer!=null) {
			super.wait();
		}
		Thread.sleep(100);
		computer=new Computer("战神",10000.0);
		System.out.println("生产电脑");
		//this.flag=false;
		super.notifyAll();
	}
	public synchronized void get() throws Exception {
		if(this.computer==null) {
			super.wait();
		}
		Thread.sleep(100);
		System.out.println();
		System.out.println("取走电脑\n"+computer.toString());
		this.computer=null;
		//flag=true;
		super.notifyAll();
	}
}
class Computer{
	private static int count=0;
	private String name;
	private double price;
	public Computer(String name,double price) {
		this.name=name;
		this.price=price;
		count++;
	}
	public String toString() {
		return "第"+count+"台电脑:name:"+this.name+"price:"+price;
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值