生产电脑和取出电脑
只有生产出电脑,才能取出,没有取出则不能生产,没有生产则不能取出。
package demo;
class Producers implements Runnable{
private Resource resource;
public Producers(Resource resource) {
// TODO Auto-generated constructor stub
this.resource = resource;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 50; i++) {
try {
this.resource.make();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
private Resource resource;
public Consumer(Resource resource) {
// TODO Auto-generated constructor stub
this.resource = resource;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 50; i++) {
try {
this.resource.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Resource {
private Computer computer;
public synchronized void make() throws InterruptedException {
if(this.computer != null) {
super.wait();
}
Thread.sleep(100);
this.computer = new Computer("联想拯救者", 5600);
System.out.println("【生产电脑】" + this.computer);
super.notifyAll();
}
public synchronized void get() throws InterruptedException {
if(this.computer == null) {
super.wait();
}
Thread.sleep(10);
System.out.println("【取走电脑】" + this.computer);
this.computer = null;
super.notifyAll();
}
}
class Computer{
private static int count = 0;
private String name;
private double price;
public Computer(String name,double price) {
// TODO Auto-generated constructor stub
this.name = name;
this.price = price;
count ++ ;
}
public String toString() {
return "【第" + count + "台电脑】" + "电脑名字;" + this.name + ",价值:" + this.price;
}
}
public class Miniusb {
public static void main(String[] args) {
Resource resource = new Resource();
new Thread(new Producers(resource)).start();
new Thread(new Consumer(resource)).start();
}
}