Java实现多生产者多消费者模型
信号量方式
import java.util.concurrent.Semaphore;
public class Demo3 {
static Semaphore mutex = new Semaphore(1);
static Semaphore apple = new Semaphore(0);
static Semaphore orange = new Semaphore(0);
static Semaphore plate = new Semaphore(1);
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
Thread dad = new Thread(new Dad());
dad.setName("dad-" + i);
dad.start();
Thread daughter = new Thread(new Daughter());
daughter.setName("daughter-1" + i);
daughter.start();
Thread mother = new Thread(new Mother());
mother.setName("mother-" + i);
mother.start();
Thread son = new Thread(new Son());
son.setName("son-" + i);
son.start();
}
}
static class Dad implements Runnable {
static int setAppleNum = 0;
@Override
public void run() {
while (true) {
try {
plate.acquire();
mutex.acquire();
apple.release();
setAppleNum++;
System.out.println(Thread.currentThread().getName() + "父亲向盘子里放了第" + setAppleNum + "个苹果");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
mutex.release();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
static class Daughter implements Runnable {
static int getAppleNum = 0;
@Override
public void run() {
while (true) {
try {
apple.acquire();
mutex.acquire();
getAppleNum++;
System.out.println(Thread.currentThread().getName() + "女儿取出了第" + getAppleNum + "个苹果");
plate.release();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
mutex.release();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
static class Mother implements Runnable {
static int setOrangeNum = 0;
@Override
public void run() {
while (true) {
try {
plate.acquire();
mutex.acquire();
orange.release();
setOrangeNum++;
System.out.println(Thread.currentThread().getName() + "母亲向盘子里放了第" + setOrangeNum + "个橘子");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
mutex.release();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
static class Son implements Runnable {
static int getOrangeNum = 0;
@Override
public void run() {
while (true) {
try {
orange.acquire();
mutex.acquire();
getOrangeNum++;
System.out.println(Thread.currentThread().getName() + "儿子取出了第" + getOrangeNum + "个橘子");
plate.release();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
mutex.release();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}