//设计一个生产电脑和搬运电脑类,要求生产出一台电脑就搬走一台电脑,如果没有新的电脑生产出来,
// 则搬运工要等待新电脑产出;如果生产出的电脑没有搬走,则要等待电脑搬走后再生产,
// 并统计出生产的电脑数量
import java.rmi.server.ExportException;
import java.util.TreeMap;
class Computer{
private String mold = "Computer";
private String name;
private int count = 1; //用来统计生产的数量
private boolean flag = true;
public synchronized void setName(){
if (!flag){
try{
super.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
name = mold + count;
count++;
flag = false;
super.notify();
}
public synchronized void getName(){
if (flag){
try{
super.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
System.out.println(this.name);
flag = true;
super.notify();
}
}
class Producer implements Runnable{
Computer com = null;
public Producer(Computer com){
this.com = com;
}
public void run(){
for (int i = 0;i < 10;i++){
com.setName();
}
}
}
class Consumer implements Runnable{
Computer com = null;
public Consumer(Computer com){
this.com = com;
}
public void run(){
for (int i = 0;i < 10;i++){
com.getName();
}
}
}
public class Main{
public static void main(String[] args) {
Computer c = new Computer();
Producer pro = new Producer(c);
Consumer con = new Consumer(c);
new Thread(pro).start();
new Thread(con).start();
}
}
《JAVA开发实战经典》P311练习
最新推荐文章于 2022-06-22 10:29:25 发布