黑马程序员技术交流社区
标题:
看书写了一个死锁的模拟,还是没有出现死锁现象
[打印本页]
作者:
KK要有光
时间:
2015-5-12 00:13
标题:
看书写了一个死锁的模拟,还是没有出现死锁现象
看书模拟了一个经典的死锁程序,可是还是没有出现死锁现象,这是代码。
public class DeadLock {
/**
* @param args
*/
static String knife="餐刀",fork="叉子";
static class A extends Thread{
public void run(){
synchronized(knife){
System.out.println("甲拿起了"+knife+",等待"+fork+"...");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
synchronized(fork){
}
System.out.println("甲又拿起了"+fork);
}
}
}
}
static class B extends Thread{
public void run(){
synchronized(fork){
System.out.println("乙拿起了"+fork+",等待"+fork+"...");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
synchronized(knife){
System.out.println("乙又拿起了"+knife);
}
}
}
}
static class Demo extends Thread{
public Demo(){
this.setDaemon(true);
}
public void run(){
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println("守护线程:程序正在运行中...");
}
}
}
public static void main(String[] args) {
new A().start();
new B().start();
new Demo().start();
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2