Java 多线程经典问题-生产者与消费者实例

2、设计一个生产计算机和搬运计算机类,要求生产出一台电脑就搬走一台,如果没有新的计算机生产出来,则搬运工要等待新计算机产出; 如多生产出的计算机没有搬走,则要等待计算机搬走之后再生产,并统计出生产的计算机数量。

public class T2 {
	public static void main(String[] args) {
		Info i = new Info();
		Producer pr = new Producer(i);
		Consumer co = new Consumer(i);
		Thread p = new Thread(pr);
		Thread c = new Thread(co);
		p.start();
		c.start();
	}
}

class Info{				//定义信息类
	private String name;
	private int count=0;
	private boolean flag = false;
	public synchronized void set(String name) {
		if(!flag) {
			try {
				super.wait();
			}catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.setName(name);
		this.count++;
		flag = false;
		super.notify(); 						//唤醒线程
	}
	public synchronized void get() {
		if(flag) {
			try {
				super.wait();
			}catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("搬走-->"+this.getName());
		flag = true;
		super.notify();
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getName() {
		return this.name;
	}
	public int getCount() {
		return this.count;
	}
	public void setCount(int count) {
		this.count = count;
	}
}

//生产电脑
class Producer implements Runnable{
	private Info info;
	private int count = 1;
	public Producer(Info info) {
		this.info = info;
	}
	public void run() {
		for(int i=0;i<10;i++) {
			this.info.set("Computer"+count);
			count++;
		}
	}
}


//搬走电脑
class Consumer implements Runnable{
	Info info;
	public Consumer(Info info) {
		this.info=info;
	}
	public void run() {
		for(int i=0;i<10;i++) {
			this.info.get();
		}
	}
}

运行结果:
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值