生产电脑
题目:设计一个生产电脑和搬运电脑类,要求生产出一台电脑就搬走一台电脑,如果没有新的电脑生产出来,则搬运工要等待新电脑产出,如果生产出的电脑没有搬走,则要等待电脑搬走之后再生产,并统计出生产的电脑数量。
public class ComputerTest {
public static void main(String[] args) {
Resource resource = new Resource();
ProducerComThread pro = new ProducerComThread(resource);
ConsumerComThread con = new ConsumerComThread(resource);
new Thread(pro, "生产者线程").start();
new Thread(con, "消费者线程").start();
}
}
class ConsumerComThread implements Runnable {
private Resource resource;
public ConsumerComThread(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
try {
resource.consumer();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
class ProducerComThread implements Runnable {
private Resource resource;
public ProducerComThread(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
try {
if (i % 2 == 0) {
resource.producer("联想");
} else
resource.producer("华为");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
class Resource {
private Computer computer;
public synchronized void producer(String name) throws InterruptedException {
while (computer != null)
super.wait();
Thread.sleep(200);
this.computer = new Computer(name);
System.out.println("[" + Thread.currentThread().getName() + "] - " + computer.getName());
super.notifyAll();
}
public synchronized String consumer() throws InterruptedException {
while (computer == null)
super.wait();
Thread.sleep(200);
System.out.println("[" + Thread.currentThread().getName() + "] - " + computer.getName());
System.out.println(this.computer);
try {
return computer.getName();
} finally {
computer = null;
super.notifyAll();
}
}
public Computer getComputer() {
return computer;
}
}
class Computer {
private String name;
private static int count = 0;
public Computer (String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "【这是第"+ ++count + "台电脑】"+" - 电脑型号是:"+this.name;
}
}
这里思路是定义一个电脑类,再定义一个线程管理类,用线程管理电脑,再构建消费者与生产者。