2019-07-05
1 回答
package 试试;
import java.util.concurrent.Semaphore;
public class GuaiAndQi {
Semaphore bowl = new Semaphore(1);//用来获得小碗的控制权(主人和两只小狗不能同时放食物或者吃)
int count = 0;//为碗里的狗粮计数
class guaiGuai implements Runnable {//乖乖的线程
public void run() {
while(true){
try {
if(count>0) {
bowl.acquire();//获得碗的控制权
count--;//吃一个狗粮
System.out.println(" 乖乖吃了一个狗粮,当前剩余狗粮为:"+count);
bowl.release();//释放碗的控制权
Thread.sleep(1000);//消食一秒钟(单位是ms)
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class qiQi implements Runnable {//奇奇的线程
public void run() {
while(true){
try {
if(count>0) {
bowl.acquire();//获得碗的控制权
count--;//吃一个狗粮
System.out.println("奇奇吃了一个狗粮,当前剩余狗粮为:"+count);
bowl.release();//释放碗的控制权
Thread.sleep(2000);//消食两秒钟
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class master implements Runnable {//主人的线程
public void run() {
while(true){
try {
bowl.acquire();//获得碗的控制权
count=count+5;//向碗里放五个狗粮
System.out.println(" 主人放了五个狗粮,当前剩余狗粮为:"+count);
bowl.release();//释放碗的控制权
Thread.sleep(3000);//等待三秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
GuaiAndQi gaq=new GuaiAndQi();
new Thread(gaq.new master()).start();
new Thread(gaq.new qiQi()).start();
new Thread(gaq.new guaiGuai()).start();
}
}//两只狗吃完消食的时间我设置的不一样,这个你可以自己设置一下。我也是一个学生小白,来试试,共同进步。望采纳。
举报