黑马程序员技术交流社区
标题:
死锁测试没预期效果
[打印本页]
作者:
赵学刚
时间:
2012-12-1 16:49
标题:
死锁测试没预期效果
本帖最后由 赵学刚 于 2012-12-3 12:58 编辑
/**
* 死锁测试
*/
public class test6 implements Runnable {
private boolean flag;
test6(boolean flag){
this.flag=flag;
}
@Override
public void run() {
if(flag){ while(true){
synchronized(MyLock.locka){
System.out.println("if locka");
synchronized(MyLock.lockb){
System.out.println("if lockb");
}
}
}
}
else{ while(true){
synchronized(MyLock.lockb){
System.out.println("else lockb");
synchronized(MyLock.locka){
System.out.println("else locka");
}
}
}
}
}
static class MyLock {
static Object locka=new Object();
static Object lockb=new Object();
}
public static void main(String[] args) {
Test6 t=new Test6(true);
Thread t1=new Thread(t);
Thread t2=new Thread(t);
t1.start();
t2.start();
}
}
为什么不会死锁,而是一直打印不会停呢
作者:
刘子义
时间:
2012-12-2 10:51
1、始终没有改变flag的值
2、你的if判断在while循环外,即使在循环中改变了flag值,也不会走到else里
稍微改下run方法:
int x = 0;
while (true) {
if (x == 0) {
synchronized (MyLock.locka) {
System.out.println("if locka");
synchronized (MyLock.lockb) {
System.out.println("if lockb");
}
}
} else {
synchronized (MyLock.lockb) {
System.out.println("else lockb");
synchronized (MyLock.locka) {
System.out.println("else locka");
}
}
}
x = (x + 1) % 2;
}
作者:
赵学刚
时间:
2012-12-2 11:17
嗯 谢谢 根据你给的提示 多加了个传入对象
Thread t1=new Thread(new Test6(true));
Thread t2=new Thread(new Test6(false));
t1.start();
t2.start();
现在可以运行了
作者:
赵学刚
时间:
2012-12-3 00:08
问题已解决
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2