每次随机生产数量的商品,保证每次剩余的商品数量不能超过1000,每次消费随机数量商品,保证生产和消费交替执行
240 | 240 |
100 | 140 |
500 | 640 |
430 | 210 |
600 | 810 |
等待唤醒机制(结合锁来使用)
通过wait、notify以及标志位来控制线程对象的执行顺序
代码如下(数据产生,根据需要,请自行停止程序):
/**
* 线程--消费生产模型
* 通过程序控制线程间的执行顺序 (等待唤醒机制,结合锁来使用):wait() ,notify() 及标志位
*/
public class ThreadTest {
public static void main(String[] args) {
//商品类对象
Product p = new Product();
//创建线程对象
new Thread(new Productor(p),"生产者").start();
new Thread(new Consumer(p),"消费者").start();
}
}
//代表生产者
//代表线程任务的信息---生产过程
class Productor implements Runnable{
// 注入商品类对象
Product p ;
//有参构造
public Productor(Product p) {
this.p = p;
}
//重写方法--描述生产过程
@Override
public void run() {
while (true){
//加锁
synchronized (p){
//线程等待
if (p.flag==false)
try {
p.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
//随机生产的商品数量
int count = (int) (Math.random()*(1000-p.getCount()+1));
//设置新的剩余商品数量
p.setCount(p.getCount()+count);
//输出
System.out.println(Thread.currentThread().getName()
+"生产了"+count+"个商品,还剩余"+p.getCount()+"个商品");
//唤醒消费线程对象
p.notify();
//改变标志位的值
p.flag = false;
}
}
}
}
//代表消费者
//代表线程任务信息---消费的过程
class Consumer implements Runnable{
//注入商品类对象
Product p;
//有参构造
public Consumer(Product p) {
this.p = p;
}
//重写方法--实现消费
@Override
public void run() {
while (true){
synchronized (p){
if (p.flag==true)
//线程等待
try {
p.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
//随机消费的商品数量
int count = (int) (Math.random()*(p.getCount()+1));
//设置剩余的商品数量
p.setCount(p.getCount()-count);
//输出
System.out.println(Thread.currentThread().getName()+"消费了"
+count+"个商品,还剩余"+p.getCount()+"个商品");
//唤醒等待的线程
p.notify();
//设置标志位
p.flag = true;
}
}
}
}
//代表商品
class Product{
//商品数量
private int count;
//标志位
boolean flag = true;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}