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();
}
}
}
运行结果: