设置一个生产电脑和搬运电脑类,要求生产出一台电脑就搬走一台电脑,如果没有新电脑产出,则搬运等待,如果生产的没有搬走,则要等待电脑搬走之后再生产,并统计地产电脑的电脑数量。
生产者消费者问题
package wzr.thread.test2;
public class ComputerSell {
public static void main(String[] args) {
Resource res=new Resource();
new Thread(new Producer(res)).start();
new Thread(new Consumer(res)).start();
}
}
class Producer implements Runnable{
private Resource resource;
public Producer(Resource resource) {
this.resource=resource;
}
public void run() {
for(int x=0;x<50;x++) {
try {
resource.make();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
private Resource resource;
public Consumer(Resource resource) {
this.resource=resource;
}
public void run() {
for(int x=0;x<50;x++) {
try {
resource.get();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Resource{
private Computer computer;
//private boolean flag=true;
public synchronized void make()throws Exception {
if(computer!=null) {
super.wait();
}
Thread.sleep(100);
computer=new Computer("战神",10000.0);
System.out.println("生产电脑");
//this.flag=false;
super.notifyAll();
}
public synchronized void get() throws Exception {
if(this.computer==null) {
super.wait();
}
Thread.sleep(100);
System.out.println();
System.out.println("取走电脑\n"+computer.toString());
this.computer=null;
//flag=true;
super.notifyAll();
}
}
class Computer{
private static int count=0;
private String name;
private double price;
public Computer(String name,double price) {
this.name=name;
this.price=price;
count++;
}
public String toString() {
return "第"+count+"台电脑:name:"+this.name+"price:"+price;
}
}