import java.util.concurrent.Semaphore;
public class produceanduse {
static Integer count = 0;
final Semaphore empty=new Semaphore(10);
final Semaphore full=new Semaphore(0);
final Semaphore mutex = new Semaphore(1);
class Producer implements Runnable {
public void run() {
try {
empty.acquire();
mutex.acquire();//-1
count++;
System.out.println(Thread.currentThread().getName() + "生产者生产,目前总共有" + count);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
full.release();//+1
mutex.release();
}
}
}
class Consumer implements Runnable {
public void run() {
try {
full.acquire();
mutex.acquire();
count--;
System.out.println(Thread.currentThread().getName() + "消费者消费,目前总共有" + count);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
empty.release();
mutex.release();
}
}
}
public static void main(String[] args) {
produceanduse pc = new produceanduse();
new Thread(pc.new Producer()).start(); //启动5个生产者线程和5个消费者线程,模拟生产者、消费者并发执行
new Thread(pc.new Consumer()).start();
new Thread(pc.new Producer()).start();
new Thread(pc.new Consumer()).start();
new Thread(pc.new Producer()).start();
new Thread(pc.new Consumer()).start();
new Thread(pc.new Producer()).start();
new Thread(pc.new Consumer()).start();
}
}
/*
* 定义两个同步信号量:
empty——表示缓冲区是否为空,初值为1。
full——表示缓冲区中是否为满,初值为0。
生产者进程
while(TRUE){
生产一个产品;
P(empty);
产品送往Buffer;
V(full);
}
消费者进程
while(TRUE){
P(full);
从Buffer取出一个产品;
V(empty);
消费该产品;
*
*
*
*
*
*
* */
*/
【水汐の操作系统】生产者消费者问题(java)
最新推荐文章于 2024-02-03 11:46:49 发布