学习到线程这章,自己写了个生产者消费者问题。
模拟的是电脑的生产和消费。
模拟的是电脑的生产和消费。
package thread;
class Computer {
private int id;
Computer(int id) {
this.id = id;
}
//override the method toString() from Object
public String toString() {
return "Computer:[" + id + "]";
}
}
class Factory {
private int items = 0;
Computer[] computer;
Factory() {
computer = new Computer[6];
}
public synchronized void push(Computer comp) {
while (items == computer.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
computer[items++] = comp;
// items++;
}
public synchronized Computer pop() {
while (items == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
return computer[--items];
}
}
class Ibm implements Runnable {
Factory fac = null;
Ibm(Factory f) {
this.fac = f;
}
public void run() {
for (int i = 0; i < 20; i++) {
Computer com = new Computer(i);
fac.push(com);
System.out.println("IBM assemble one computer " + com);
try {
Thread.sleep((long) (Math.random()*100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Kisters implements Runnable {
Factory fac = null;
Kisters(Factory f) {
this.fac = f;
}
public void run() {
for (int i = 0; i < 20; i++) {
Computer com = fac.pop();
System.out.println("Kisters consume one computer " + com);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ProducerConsumer {
public static void main(String[] args) {
Factory fac = new Factory();
Ibm ibm = new Ibm(fac);
Kisters kis = new Kisters(fac);
Thread t1 = new Thread(ibm);
Thread t2 = new Thread(kis);
t1.start();
t2.start();
}
}