生产者消费者问题(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();
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值