class DeadLock implements Runnable {
public DeadLock(String ch, String tag) {
this.ch = ch;
this.tmptag = tag;
}
static String tag = "A";
String tmptag = "";
public int flag = 1;
String ch = "";
static Object o1 = new Object(), o2 = new Object();
public void run() {
while (true) {
// System.out.println("debug"+ch);
// System.out.println("debug_"+this.tag);
// System.out.println("debug1"+ch);
synchronized (o1) {
if (tag.equals(ch)) {
try {
System.out.println("real" + ch);
tag = tmptag;
o1.notify();
o1.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) throws InterruptedException {
DeadLock td1 = new DeadLock("A", "B");
DeadLock td2 = new DeadLock("B", "C");
DeadLock td3 = new DeadLock("C", "A");
new Thread(td1).start();
Thread.sleep(200);
new Thread(td2).start();
Thread.sleep(200);
new Thread(td3).start();
}
}
这里注意的是
正确代码:
<span style="color:#FF0000;">while 后边应该是直接跟sync 去block住当前线程的,如果是里面再是判断 ,如下变代码试例。 则每个线程都会因为不停的while而大量消耗机器资源
</span>
while (true) {<span style="color:#FF0000;"> //while 后边应该是直接跟sync 去block住当前线程的,如果是里面再是判断 ,如下变代码试例。 则每个线程都会因为不停的while而大量消耗机器资源</span>
synchronized (o1) {
if (tag.equals(ch)) {
try {
System.out.println("real" + ch);
tag = tmptag;
o1.notify();
o1.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
错误代码:
while (true) {
if (tag.equals(ch)) {<span style="color:#FF0000;"> //当一段时间内为false时 ,这里会白白消耗大量资源,消耗cpu</span>
synchronized (o1) {
try {
System.out.println("real" + ch);
tag = tmptag;
o1.notify();
o1.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
这个案例可以作为一个 bug Analysis