附程序如下:
package TestThread1;
/**
- Mission : 设计一个生产电脑 和搬运电脑类,要求生产出一台电脑就搬走一台,如果没有新的电脑产出,则要等待新的电脑产出;如果产出的电脑没有搬走
- 则要等待电脑搬走之后再生产,并统计出生产的电脑数量。
- @author Administrator * */
public class ThreadDemo10 {
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 {
this.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 {
this.resource.get();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Resource {
private int in=0;
private Computer computer;
public synchronized void make() throws Exception{
if(this.computer!=null) {
super.wait();
}else {
Thread.sleep(100);
this.computer=new Computer("MLDB牌电脑",1.1);
System.out.println("生成一台电脑"+this.computer);
System.out.println("制造者唤醒其他线程");
super.notifyAll();
}
}
public synchronized void get() throws Exception {
System.out.println("进入 get()");
if(this.computer==null) { //没有生产过
in++;
Thread.currentThread().setName("制造者AAAAAAAAAAAAAAAAAAA"+" "+in);
System.out.println(Thread.currentThread().getName() + " 阻塞");
super.wait();
}
else {
System.out.println("被Producer线程唤醒,已经可以取电脑了");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("取走电脑"+this.computer);
this.computer=null;
super.notify();
}
System.out.println("从wait()之后开始执行,因为已经执行了if,故不会执行else.----此处表明等待中的线程是由wait之后开始执行");
}
}
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+"台电脑】"+"电脑名字 "+this.name+"、价值."+this.price;
}
}