您的位置:首页 > 编程语言 > Java开发

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

2016-07-06 10:02 585 查看
<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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息