Disclaimer: This article is a blogger original article. Reproduced please contact bloggers authorization. Bloggers public micro-channel number] [Department of Knowing and Doing the campus. https://blog.csdn.net/cxh_1231/article/details/86481718
Note : This article documents WHUT- Computer College - courses on operating system Experiment 2: Process Management
Paper come Zhongjue, practice is essential to be aware of the matter!
1. Experiment:
Experimental preparation: to master the content process management, synchronization and mutex, semaphore mechanism to process and have a deep understanding of
Experiment: simulate a settlement dining philosophers problem using semaphore mechanism (or other classical synchronization problems)
Specific requirements:
- Choose one high-level computer programming language
- Achieve 5 philosopher ( 5 Zhi chopsticks) smoothly dining
- The need to avoid deadlock
- Using semaphore, the semaphore wait queue and
- Using the P operator, V operation
- Each display can be philosophers, and status of each of chopsticks
2, run shot:
3, the source code:
package test2;
/*每个哲学家安排一个线程*/
class Philosopher extends Thread{
private String name;
private Chopsticks Chopsticks;
public Philosopher(String name,Chopsticks Chopsticks){
super(name);
this.name=name;
this.Chopsticks=Chopsticks;
}
//重构
public void run(){
while(true){
//哲学家的状态就是:思考→进餐→思考 循环
thinking();
Chopsticks.P();
eating();
Chopsticks.V();
}
}
public void eating(){
int i = Integer.parseInt(name);
System.out.println("哲学家 " + name + "号 开始拿着筷子 "+ i +" 和 "+ (i+1)%5 + "进餐!");//打印哲学家状态和筷子状态
try {
sleep(2000);//假设吃饭时间为5秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void thinking(){
System.out.println("哲学家 " + name + "号 陷入了思考!");
try {
sleep(2000);//假设思考4秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Chopsticks{
/*5只筷子,初始为1,即未被用*/
private int[] ChopStatus={1,1,1,1,1};
//避免死锁
/*P操作:只有当左右手的筷子都未被使用时,才允许获取筷子,且必须同时获取左右手筷子*/
public synchronized void P(){
//获得当前线程的名字(哲学家)
String name = Thread.currentThread().getName();
int i = Integer.parseInt(name);
//当当前线程哲学家左右手的筷子已经被占用
while(ChopStatus[i]==0||ChopStatus[(i+1)%5]==0){
try {
System.out.println("哲学家 "+ name +"号 正在等待筷子!");
//当前哲学家线程进入等待状态
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//获得左右筷子,修改筷子状态
ChopStatus[i]-=1 ;
ChopStatus[(i+1)%5]-=1;
}
/*V操作:同时释放左右手的筷子*/
public synchronized void V(){
//获得当前线程的名字(哲学家)
String name = Thread.currentThread().getName();
int i = Integer.parseInt(name);
//释放左右筷子
ChopStatus[i]+=1;
ChopStatus[(i+1)%5]+=1;
//唤醒等待序列中的线程
notifyAll();
}
}
public class Think_Eat {
public static void main(String []args){
Chopsticks Chopsticks = new Chopsticks();
new Philosopher("0",Chopsticks).start();
new Philosopher("1",Chopsticks).start();
new Philosopher("2",Chopsticks).start();
new Philosopher("3",Chopsticks).start();
new Philosopher("4",Chopsticks).start();
}
}