多线程经典之生产者与消费者

<strong>package PAndC;

public class C {
	private Service service;
	public void eat(Service service) throws InterruptedException{
		
		
		synchronized (service) {
			if(Service.restoreValue.equals("")){
				service.wait();
			}
			System.out.println("吃" + Service.restoreValue);
			Service.restoreValue = "";
			service.notify();
		}
		
	}
}






package PAndC;

public class P {
	
	private Service service;
	public void create(Service service) throws InterruptedException{
		
		synchronized (service) {
			if(!Service.restoreValue.equals("")){
				service.wait();
			}
			String time = System.currentTimeMillis() + "";
			System.out.println("生产 " + time);
			service.restoreValue = time;
			service.notify();
		}
	}
}




package PAndC;

public class Service {
	public static String restoreValue = "";
}



package PAndC;

public class ThreadC extends Thread{
	private C c;
	private Service service;
	
	public ThreadC(Service service, C c){
		this.service = service;
		this.c = c;
	}
	public void run(){
		while(true){
			try {
				c.eat(service);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}



package PAndC;

public class ThreadP extends Thread{
	
	private Service service;
	private P p;
	public ThreadP(Service service, P p){
		this.service = service;
		this.p = p;
	}
	public void run(){
		while(true){
			try {
				p.create(service);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}

	}
}



package PAndC;

public class TestMain {

	public static void main(String[] args) throws InterruptedException {
		Service service = new Service();
		P p = new P();
		C c = new C();
		
		ThreadC threadC = new ThreadC(service, c);
		threadC.start();
		
		Thread.sleep(1000);
		
		ThreadP threadP = new ThreadP(service, p);
		threadP.start();
	}
}

</strong>
<strong>没懂的问我下  wechat: wangyan199366</strong>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值