实验了很多此就是不死锁, 不知道是不是锁字符串对象的原因
package com.哲学家进餐;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @ClassName 死锁的问题
* @Description TODO
* @Author Shinelon
* @Date DATE 2021/8/4 10:16
*/
public class 死锁的问题 {
static String[] fork = {"fork1",
"fork2","fork3"
,"fork4","fork5"};
static class Task implements Runnable{
String lfork;
String rfork;
public String getLfork() {
return lfork;
}
public void setLfork(String lfork) {
this.lfork = lfork;
}
public String getRfork() {
return rfork;
}
public void setRfork(String rfork) {
this.rfork = rfork;
}
public Task(String lfork, String rfork){
this.lfork=lfork;
this.rfork=rfork;
}
@Override
public void run() {
//锁lfork
synchronized (this.lfork){
//锁rfork
synchronized (this.rfork){
System.out.println("eating");
}
}
}
}
//5个线程
public static void main(String[] args) {
Task[] tasks = new Task[5];
tasks[0] = new Task(fork[0],fork[1]);
tasks[1] = new Task(fork[1],fork[2]);
tasks[2] = new Task(fork[2],fork[3]);
tasks[3] = new Task(fork[3],fork[4]);
tasks[4] = new Task(fork[4],fork[0]);
ExecutorService executorService = Executors.newFixedThreadPool(5);
int k=0;
for (int i = 0; i < 5; i++) {
executorService.execute(tasks[i]);
}
executorService.shutdown();
}
}