/**
* 生产者消费者例子
* @author MrYang
*
*/
public class Test {
private int p = 0 ;
class Warehouse {
Object[] o = null ;
public Warehouse(int length){
o = new Object[length];
}
int index = 0 ;
public synchronized void addProduct(){
if(index == o.length){
try {
this.wait() ;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o[index] = new Object() ;
index ++;
this.notify() ;
p++;
System.out.println("生成了一个产品,剩余数量:"+p);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void reduceProduct(){
if(index== 0){
try {
this.wait() ;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
index -- ;
this.notify();
p-- ;
System.out.println("消费了一个产品,剩余数量:"+p);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Consumer implements Runnable{
Warehouse warehouse = null ;
public Consumer(Warehouse w){
warehouse = w ;
}
public void run(){
for(int i = 0 ; i < 10 ; i++){
warehouse.reduceProduct();
}
}
}
class Producer implements Runnable{
Warehouse warehouse = null ;
public Producer(Warehouse w){
warehouse = w ;
}
public void run(){
for(int i = 0 ; i < 10 ; i++){
warehouse.addProduct();
}
}
}
public void run(){
Warehouse wa = new Warehouse(4);
Thread c = new Thread(new Consumer(wa));
Thread p = new Thread(new Producer(wa));
p.start();
c.start();
}
public static void main(String[] args){
Test t = new Test();
t.run();
}
}
Java生产者消费者代码
最新推荐文章于 2025-07-04 00:15:00 发布