哲学家吃面问题,下图有五个哲学家,五根筷子,如果每个人都先拿自己右手边的筷子,那大家左手边就没有筷子了。哲学家吃面问题(死锁)
看一个简单的死锁程序:
package deadlock;
import java.util.concurrent.TimeUnit;
public class ThreadDemo5
{
public static Integer r1 = 1;
public static Integer r2 = 2;
public static void main(String args[]) throws InterruptedException
{
TestThread51 t1 = new TestThread51();
t1.start();
TestThread52 t2 = new TestThread52();
t2.start();
}
}
class TestThread51 extends Thread
{
public void run()
{
//先要r1,再要r2
synchronized(ThreadDemo5.r1)
{
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(ThreadDemo5.r2) //r2被TestThread52占用
{
System.out.println("TestThread51 is running");
}
}
}
}
class TestThread52 extends Thread
{
public void run()
{
//保持同样的顺讯,先要r1,再要r2
synchronized(ThreadDemo5.r2)
try {
TimeUnit.SECONDS.sleep(3);//跟直接用thread sleep差不多
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(ThreadDemo5.r1)//r1被TestThread51占用 造成死锁
{
System.out.println("TestThread52 is running");
}
}
}
}
解决上边死锁问题,对资源进行等级访问,(比如TestThread51和TestThread52都是先r1后r2,顺序一样就没问题了。)
如下改法就没问题了:
package deadlock;
import java.util.concurrent.TimeUnit;
public class ThreadDemo5
{
public static Integer r1 = 1;
public static Integer r2 = 2;
public static void main(String args[]) throws InterruptedException
{
TestThread51 t1 = new TestThread51();
t1.start();
TestThread52 t2 = new TestThread52();
t2.start();
}
}
class TestThread51 extends Thread
{
public void run()
{
//先要r1,再要r2
synchronized(ThreadDemo5.r1)
{
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(ThreadDemo5.r2)
{
System.out.println("TestThread51 is running");
}
}
}
}
class TestThread52 extends Thread
{
public void run()
{
//先要r2,再要r1
synchronized(ThreadDemo5.r1)
{
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(ThreadDemo5.r2)
{
System.out.println("TestThread52 is running");
}
}
}
}