多线程情况下,同步代码块的嵌套容易出现死锁,也就是我们熟知的哲学家就餐问题,总结一下:
package test;
/**
* @author: taibai
* @date:2019/10/20
*/
public class DeadLock {
public static void main(String[] args) {
String s1 = "筷子1";
String s2 = "筷子2";
String s3 = "筷子3";
String s4 = "筷子4";
String s5 = "筷子5";
new Thread() {
@Override
public void run() {
while (true) {
synchronized (s1) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + "拿到筷子1等待筷子2");
synchronized (s2) {
System.out.println(getName() + "拿到筷子2开吃");
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
while (true) {
synchronized (s2) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + "拿到筷子2等待筷子3");
synchronized (s3) {
System.out.println(getName() + "拿到筷子3开吃");
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
while (true) {
synchronized (s3) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + "拿到筷子3等待筷子4");
synchronized (s4) {
System.out.println(getName() + "拿到筷子4开吃");
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
while (true) {
synchronized (s4) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + "拿到筷子4等待筷子5");
synchronized (s5) {
System.out.println(getName() + "拿到筷子5开吃");
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
while (true) {
synchronized (s5) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + "拿到筷子5等待筷子1");
synchronized (s1) {
System.out.println(getName() + "拿到筷子1开吃");
}
}
}
}
}.start();
}
}
设置一定的睡眠时间能够让结果更明显。

2041

被折叠的 条评论
为什么被折叠?



