1.仓库Storage.java
[代码]java代码:
?
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | package demo03;
public class Storage {
private final static int MAX_NUM=1000;// 仓库最大的储存数量
private int store;// 目前仓库存储的数量
public Storage(int store){
this.store=store;
}
// 入库操作
public synchronized void in(int num){
String threadName=Thread.currentThread().getName();
if(this.store+num>MAX_NUM){
System.out.println(threadName+" 被挂起!");
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.store+=num;// 入库
this.notifyAll();// 唤醒等待线程
System.out.println(threadName+" 生成产品数量为:"+num+" 仓库现在的数量为:"+this.store);
}
// 出库操作
public synchronized void out(int num){
String threadName=Thread.currentThread().getName();
if(this.store<num){ system.out.println(threadname+" 被挂起!");="" try="" {="" this.wait();="" }="" catch="" (interruptedexception="" e)="" todo="" auto-generated="" block="" e.printstacktrace();="" this.store-="num;// 出库" this.notify();="" 唤醒等待的线程="" system.out.println(threadname+" 消费产品数量为:"+num+"="" 仓库现在的数量为:"+this.store);="" }<="" pre=""></num){>
|
2.生产者 Producter.java
[代码]java代码:
?
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 | package demo03;
public class Producter extends Thread{
private int num;// 入库数量
private Storage store;
public Producter(int num,Storage store){
this.num=num;
this.store=store;
}
@Override
public void run() {
this.store.in(num);// 入库
}
}
|
3.消费者Customer.java
[代码]java代码:
?
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | package demo03;
public class Customer extends Thread{
private int num;// 出库数量
private Storage store;
public Customer(int num,Storage store){
this.num=num;
this.store=store;
}
@Override
public void run() {
this.store.out(num);// 出库
}
}
4. 测试 Test.java
package demo03;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Storage store=new Storage(500);
Producter p1=new Producter(200,store);
Producter p2=new Producter(500,store);
Producter p3=new Producter(100,store);
Customer c1=new Customer(300, store);
Customer c2=new Customer(400, store);
Customer c3=new Customer(600, store);
p1.start();
p2.start();
p3.start();
c1.start();
c2.start();
c3.start();
}
}
|
原文链接:http://www.apkbus.com/blog-813041-60951.html
打开App,阅读手记