新手求教死锁问题
[code=Java][/code]
public class TestDeadLock implements Runnable
{
public int flag = 1;
public Object o1 = new Object ();
public Object o2 = new Object ();
public void run () {
System.out.println ( "flag = " + flag);
if (flag == 1) {
synchronized (o1) {
try {
Thread.sleep(5000);
}
catch (Exception e) {
e.printStackTrace ();
}
}
synchronized (o2) {
System.out.println ("1");
}
}
if (flag == 0) {
synchronized (o2) {
try {
Thread.sleep(5000);
}
catch (Exception e1) {
e1.printStackTrace ();
}
}
synchronized (o1) {
System.out.println ("0");
}
}
}
public static void main(String[] args) {
TestDeadLock tdk1 = new TestDeadLock ();
TestDeadLock tdk2 = new TestDeadLock ();
tdk1.flag = 1;
tdk2.flag = 0;
Thread t1 = new Thread (tdk1);
Thread t2 = new Thread (tdk2);
t1.start();
t2.start();
}
}
为什么结果总是
flag = 1
flag = 0
1
0
而没有形成死锁啊?????
------解决方案--------------------hi guy, (sorry, no chinese input typer)
first:you have created two different objects of Class TestDeadLock, they don't need to share a "sharing resource";
second: you didn't really lock o2
if you want to test deadlock try to change the code as bellow:
code=Java]public class TestDeadLock implements Runnable {
public int flag = 1;
public static Object o1 = new Object();
public static Object o2 = new Object();
public void run() {
System.out.println("flag = " + flag + "" + this + ">time:" + System.currentTimeMillis());
if (flag == 1) { // 1, lock o1 first
synchronized (o1) {
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (o2) {
System.out.println("1");
}
}
}
if (flag == 0) { // 0 lock o2 first
synchronized (o2) {
try {
Thread.sleep(5000);
} catch (Exception e1) {
e1.printStackTrace();
}
synchronized (o1) {
System.out.println("0");
}
}
}
}
public static void main(String[] args) {
TestDeadLock tdk1 = new TestDeadLock ();
TestDeadLock tdk2 = new TestDeadLock ();
tdk1.flag = 0;
tdk2.flag = 1;
Thread t1 = new Thread(tdk1);
Thread t2 = new Thread(tdk2);
t1.start();
t2.start();
}
}[/code]
------解决方案--------------------public int flag = 1;
public Object o1 = new Object ();
public Object o2 = new Object ();
如上3个你定义的变量是成员变量,并非类变量,这在该类的不同实例间显然是互不影响的。用static修饰下就能看到效果了
------解决方案--------------------那个例子只是可能出现死锁 我这个例子出现死锁的几率更大一些
Java code
package example;
import java.util.concurrent.atomic.AtomicInteger;
public class DeathLockExample {
public static void main(String[] args) {
final AtomicInteger x = new AtomicInteger(0);
final AtomicInteger y = new AtomicInteger(0);
new Thread() {
public void run() {
while (true) {
synchronized (x) {
synchronized (y) {
x.addAndGet(1);
}
}
System.err.println("x " + x.toString());
}
}
}.start();
new Thread() {
public void run() {
while (true) {
synchronized (y) {
synchronized (x) {
y.addAndGet(1);
}
}
System.err.println("y " + y.toString());
}
}
}.start();
}
}