描述

哲学家进餐问题描述有五个哲学家,他们的生活方式是交替地进行思考和进餐,n哲学家们共用一张圆桌,分别坐在周围的五张椅子上,在圆桌上有五个碗和五支筷子,n平时哲学家进行思考,饥饿时便试图取其左、右最靠近他的筷子,只有在他拿到两支筷子时才能进餐,n进餐完毕,放下筷子又继续思考。
约束条件
(1)只有拿到两只筷子时,哲学家才能吃饭。
(2)如果筷子已被别人拿走,则必须等别人吃完之后才能拿到筷子。
(3)任一哲学家在自己未拿到两只筷子吃饭前,不会放下手中拿到的筷子。

java线程实现

线程访问资源,加synchronized锁,并用wait和notify通知线程。总体思路就是这样,这次我的代码可读性还是很强的,自己话五分钟看看吧。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package test;
import java.lang.*;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.event.TreeWillExpandListener;
class philosopher extends Thread{
public chopsticks left,right;
public int number;
public int cnt=1;
public philosopher(int x,chopsticks c2,chopsticks c1) {
// TODO Auto-generated constructor stub
number=x;
left= c2;right= c1;
}
public void eat(){
left.takeup();
right.takeup();
System.out.println(number+"号哲学家在第"+this.cnt+"次吃饭");
try {
this.sleep((long) (Math.random()*1500+1500));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(number+"号哲学家吃好了");
this.cnt++;
left.pudown();
right.pudown();
}
public void thinking(){
System.out.println(this.number+"号哲学家在思考");
try {
this.sleep((long) (1500+Math.random()*1500));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run(){
super.run();
while(this.cnt<=3){
int x=(int) (Math.random()*3);
//哲学家随机思考或者吃饭
if(x==1)
thinking();
else
eat();
}
}
}
class chopsticks extends Thread{
public boolean available=true;
public int number;
public synchronized void takeup() {
while(this.available==false){
try {
wait();
System.out.println("请求"+this.number+"号筷子,但是它正在被另一个哲学家使用");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.available=false;
}
public synchronized void pudown(){
this.available=true;
notifyAll();
}
public chopsticks(int x) {
// TODO Auto-generated constructor stub
number=x;
}
}
public class test2 {
public static void main(String[] args){
System.out.println("philosopher 吃三次饭");
System.out.println("philosopher's dining start");
chopsticks c1= new chopsticks(1);
chopsticks c2= new chopsticks(2);
chopsticks c3= new chopsticks(3);
chopsticks c4= new chopsticks(4);
chopsticks c5= new chopsticks(5);
philosopher p1=new philosopher(1,c5,c1) ;
philosopher p2=new philosopher(2,c1,c2) ;
philosopher p3=new philosopher(3,c2,c3) ;
philosopher p4=new philosopher(4,c3,c4) ;
philosopher p5=new philosopher(5,c4,c5) ;
p2.start();
p4.start();
p1.start();
p3.start();
p5.start();
System.out.println("主线程到了尾部");
}
}

图示

哲学家吃饭