public class test5 {
static int[] b={1,1,1,1,1,1};
static int mutex=1;
public static void main(String[] args) {
new Thread(){
public void run(){
try {
pi(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread(){
public void run(){
try {
pi(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread(){
public void run(){
try {
pi(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread(){
public void run(){
try {
pi(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread(){
public void run(){
try {
pi(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
static void pi(int i) throws InterruptedException {
while (true){
if (i%2==0){
p(mutex);
p(b[i]);
p(b[(i+1)%5]);
v(mutex);
System.out.println("第"+i+"位吃饭");
v(b[i]);
v(b[(i+1)%5]);
System.out.println("第"+i+"位吃完,思考");
Thread.currentThread().sleep(3000);
}else {
p(mutex);
p(b[(i+1)%5]);
p(b[i]);
v(mutex);
System.out.println("第"+i+"位吃饭");
v(b[i]);
v(b[(i+1)%5]);
System.out.println("第"+i+"位吃完,思考");
Thread.currentThread().sleep(3000);
}
}
}
static void p(int s){
while (s<=0);
s=s-1;
}
static void v(int s){
s=s+1;
}
}