2019329621035_张浩严_homework5 Version 0 |
|
👤 Author: by 2351505710qqcom 2021-12-26 16:22:25 |
package com.company;
import java.util.concurrent.Semaphore;
public class Main {
//初始化桌子为空的信号量为1,使父亲和母亲的线程能运行,1:桌子为空 0:桌子不为空
public static Semaphore diskEmptySemaphore = new Semaphore(1);
//初始化信号量为0,使儿子和女儿线程阻塞
public static Semaphore haveOrangeSemaphore = new Semaphore(0);
public static Semaphore haveAppleSemaphore = new Semaphore(0);
public static void main(String[] args) {
Farther farther = new Farther();
Mother mother = new Mother();
Son son = new Son();
Daughter daughter = new Daughter();
farther.start();
mother.start();
son.start();
daughter.start();
}
}
class Disk {
private static String fruit = "";
public static void putFruit(String role, String fruitName) {
fruit = fruitName;
System.out.println(role + "往盘子里放入了一个" + fruit);
}
public static String getFruit(String role) {
System.out.println(role + "吃了一个" + fruit);
return fruit;
}
}
class Farther extends Thread {
String name = "父亲";
@Override
public void run() {
try {
while(true) {
Main.diskEmptySemaphore.acquire();
Disk.putFruit(name,"苹果");
sleep(1000);
Main.haveAppleSemaphore.release();
}
} catch (InterruptedException e) {
}
}
}
class Daughter extends Thread{
private String name = "女儿";
@Override
public void run() {
try {
while(true) {
Main.haveAppleSemaphore.acquire();
Disk.getFruit(name);
sleep(1000);
Main.diskEmptySemaphore.release();
}
} catch (InterruptedException e) {
}
}
}
class Mother extends Thread {
String name = "母亲";
@Override
public void run() {
try {
while(true) {
Main.diskEmptySemaphore.acquire();
Disk.putFruit(name,"桔子");
sleep(1000);
Main.haveOrangeSemaphore.release();
}
} catch (InterruptedException e) {
}
}
}
class Son extends Thread{
private String name = "儿子";
@Override
public void run() {
try {
while(true) {
Main.haveOrangeSemaphore.acquire();
Disk.getFruit(name);
sleep(1000);
Main.diskEmptySemaphore.release();
}
} catch (InterruptedException e) {
}
}
}
Please login to reply. Login