黑马程序员技术交流社区
标题:
如何创建死锁
[打印本页]
作者:
胡刚涛
时间:
2012-8-19 10:04
标题:
如何创建死锁
今天写了个程序想出现一个死锁,具体代码是:
public class TestDeadLock implements Runnable{
/**
* @param args
*/
public int flag = 2;
static Object o1 = new Object();
static Object o2 = new Object();
public void run(){
if(flag == 1){
synchronized(o1){
System.out.println("锁住o1");
try {
Thread.sleep(5000);
}catch(Exception e){}
}
synchronized(o2){
System.out.println("1");
}
}
//疑问:无法死锁
if(flag == 0){
synchronized(o2){
System.out.println("锁住o2");
try {
Thread.sleep(5000);
}catch(Exception e){}
}
synchronized(o1){
System.out.println("2");
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TestDeadLock td1 = new TestDeadLock();
TestDeadLock td2 = new TestDeadLock();
td1.flag = 1;
td2.flag = 0;
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
t1.start();
try {
Thread.sleep(5000);
} catch (Exception e) {
// TODO: handle exception
}
t2.start();
}
}
但是运行的结果没有出现死锁,代码该如何修改才能有死锁呢???求解决!!!
作者:
张忠豹
时间:
2012-8-19 10:56
package day17;
public class TestDeadLock implements Runnable{
/**
* @param args
*/
public int flag = 2;
static Object o1 = new Object();
static Object o2 = new Object();
public void run(){
if(flag == 1){
synchronized(o1){
synchronized(o2){
System.out.println("1");
}
System.out.println("锁住o1");
try {
Thread.sleep(50);
}catch(Exception e){}
}
}
//疑问:无法死锁
if(flag == 0){
synchronized(o2){
synchronized(o1
){//在synchronized块中调用synchronized块,而且它们的锁不一样,就容易造成死锁
//在synchronized修饰的函数中,调用synchronized块或方法,所不一样也能死锁
System.out.println("2");
}
System.out.println("锁住o2");
try {
Thread.sleep(50);
}catch(Exception e){}
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TestDeadLock td1 = new TestDeadLock();
TestDeadLock td2 = new TestDeadLock();
td1.flag = 1;
td2.flag = 0;
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
t1.start();
try {
Thread.sleep(50);
} catch (Exception e) {
// TODO: handle exception
}
t2.start();
}
}
作者:
胡刚涛
时间:
2012-8-19 17:43
张忠豹 发表于 2012-8-19 10:56
package day17;
public class TestDeadLock implements Runnable{
/**
ok!!!了解,明白了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2