/**
* 一个线程作为生产者,一个线程作为消费者。生产者和消费者在同时执行。
* 生产者每生产一次消费者就消费一次。生产和消费的数量用随机数来表示。
* 要求:生产者的数量和上次消费后的剩余数量和不大于1000.
* sleep:可以指定休眠的时间,如果没有其他操作,那么到点自然醒。
* 如果sleep有锁资源,那么不释放代码执行权,sleep是Thread的类方法
* wait:可以指定也可以不指定休眠时间。
* 如果有所资源,那么释放锁,也释放执行权。
* 是属于Object的方法。使用等待唤醒机制是,和notify方法配合使用
* 调用等待唤醒内容锁资源必须一致
*/
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Product p=new Product();
new Thread(new Producer(p),"生产者").start();
new Thread(new Producer(p),"生产者").start();
new Thread(new Consumer(p),"消费者").start();
new Thread(new Consumer(p),"消费者").start();
}
}
class Product{
private int count=0;
private boolean flag=true;
public synchronized void add(){
while(flag==false){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int max=1000-count;
int num=(int)(Math.random()*(max+1));
count+=num;
System.out.println(Thread.currentThread().getName()+":"+num+"缓冲池中剩余资源:"+count);
flag=false;
notifyAll();
}
public synchronized void remove(){
while(flag==true){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int num=(int)(Math.random()*(count+1));
count-=num;
System.out.println(Thread.currentThread().getName()+":"+num+"缓冲池中剩余资源:"+count);
flag=true;
notifyAll();
}
}
class Consumer implements Runnable{
private Product p;
public Consumer(Product p) {
super();
this.p = p;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
p.remove();
}
}
}
class Producer implements Runnable{
private Product p;
public Producer(Product p) {
super();
this.p = p;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
p.add();
}
}
}
Java消费者生产者问题
最新推荐文章于 2024-09-18 18:57:36 发布