一个快餐厅有4类职员:
(1)领班:接受顾客点菜;(2)厨师:准备顾客的饭菜;(3)打包工:将做好的饭菜打包;(4)出纳员:收款并提交食品。
每个职员可被看作进程,试用一种同步机制写出能让四类职员正确并发运行的程序。
public class Test1 {
private static Semaphore a = new Semaphore(1);
private static Semaphore b = new Semaphore(0);
private static Semaphore c = new Semaphore(0);
private static Semaphore d = new Semaphore(0);
public static void main(String[] args) {
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
a.acquire();
System.out.println(Thread.currentThread().getName() + "接受顾客点菜");
b.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "领班").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
b.acquire();
System.out.println(Thread.currentThread().getName() + "准备顾客的饭菜");
c.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "厨师").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
c.acquire();
System.out.println(Thread.currentThread().getName() + "将做好的饭菜打包");
d.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "打包工").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
d.acquire();
System.out.println(Thread.currentThread().getName() + "收款并提交食品");
a.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "出纳员").start();
}
}