大家帮忙看看,为什么我的代码运行起来一直都是和谐的 没有发生死锁,是不是代码有问题?
package test;
public class TestSynchronized implements Runnable{
Object a = new Object();
//Object b = new Object();
private boolean flag ;
TestSynchronized(boolean flag){
this.flag = flag;
}
@Override
public void run() {
// TODO Auto-generated method stub
if(flag)
{
while(true){
synchronized(a){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("if run a");
synchronized(this){
System.out.println("if run b");
}
}
}
}
else{
while(true){
synchronized(this){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("else run b");
synchronized(a){
System.out.println("else run a");
}
}
}
}
}
}
package test;
public class TestSynchronizedDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t1 = new Thread(new TestSynchronized(true));
Thread t2 = new Thread(new TestSynchronized(false));
t1.start();
t2.start();
}
}
|