學習到線程這章,自己寫瞭個生產者消費者問題。
模擬的是電腦的生產和消費。
Java代碼
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();
}
}
作者“燕雲十六州”