设计一个生产电脑和搬运电脑类,要求生产出一台电脑,就搬走一台电脑,如果没有新的电脑生产出来,则搬运工需要等待新电脑产出;如果生产出的电脑没有搬走,则要等待电脑搬走再生产,并统计处生产的电脑数。
在本程序中,就是一个标准的生产者和消费者的处理模型,那么下面市县具体的程序代码。
public class ThreadDemo {
public static void main(String[] args) throws Exception {
Resource res = new Resource();
Producer st = new Producer(res);
Consumer at = new Consumer(res);
new Thread(at).start();
new Thread(at).start();
new Thread(st).start();
new Thread(st).start();
}
}
class Producer implements Runnable {
private Resource resource;
public Producer(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
try {
this.resource.make();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
private Resource resource;
public Consumer(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
try {
this.resource.get();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Resource {
private Computer computer;
public synchronized void make() throws InterruptedException {
while (computer != null) {//已经生产过了
wait();
}
Thread.sleep(100);
this.computer = new Computer("DELL", 1.1);
System.out.println("【生产】" + this.computer);
notifyAll();
}
public synchronized void get() throws InterruptedException {
while (computer == null) {//已经生产过了
wait();
}
Thread.sleep(10);
System.out.println("【搬运】" + this.computer);
this.computer = null;
notifyAll();
}
}
class Computer {
private static int count;//表示生产的个数
private String name;
private double price;
public Computer(String name, double price) {
this.name = name;
this.price = price;
this.count++;
}
@Override
public String toString() {
return "【第" + count + "台电脑】电脑名字:" + this.name + "价值、" + this.price;
}
}