资源描述
命题:生产者,消费者;
1. 当商品到达10个,则停止生产;
2. 当商品为0时,则停止生产,
产品集: Products
package RunnableTest.Test2;
import java.util.Stack;
public class Products {
int counter = 0;
Stack stack;
public Products()
{
stack = new Stack();
}
public synchronized void get()
{
int item = stack.size() ;
if(item == 0)
{
try {
System.out.println("暂停消费");
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Object getS = stack.pop();
System.out.println("消费 "+getS);
this.notify();
}
public synchronized void put()
{
int item = stack.size()+1 ;
if(item>=10)
{
try {
System.out.println("暂停生产 ");
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
counter ++;
stack.push(item);
System.out.println("共生产 "+counter+";生产 "+item);
this.notify();
}
}
生产者: Produce
package RunnableTest.Test2;
public class Produce implements Runnable{
Products products;
public Produce(Products p)
{
products = p;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true)
{
try {
Thread.sleep((int)Math.random()*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
products.put();
}
}
}
消费者: Customer
package RunnableTest.Test2;
public class Customer implements Runnable{
Products products;
public Customer(Products p)
{
products = p;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true)
{
try {
Thread.sleep((int)Math.random()*900);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
products.get();
}
}
}
测试:Test2
package RunnableTest.Test2;
public class Test2 {
public static void main(String[] args)
{
Products p =new Products();//产品集
Produce produce =new Produce(p);//生产
new Thread(produce).start();
Customer customer =new Customer(p);//消费
Thread t = new Thread(customer);
t.start();
}
}
==部分结果==
共生产 1;生产 1
消费 1
暂停消费
共生产 2;生产 1
消费 1
暂停消费
共生产 3;生产 1
消费 1
共生产 4;生产 1
消费 1
共生产 5;生产 1
消费 1
共生产 6;生产 1
消费 1
………………
……………….
共生产 9406;生产 5
共生产 9407;生产 6
共生产 9408;生产 7
共生产 9409;生产 8
共生产 9410;生产 9
暂停生产
消费 9
共生产 9411;生产 10
暂停生产
消费 10
共生产 9412;生产 10
暂停生产
消费 10
展开阅读全文