程序的死锁主要是因为线程中锁定的方法过多,导致最后需要完成的一个方法,属于在另一个线程的被锁范围。
import java.io.*;
import java.lang.*;
import java.util.*;
public class hehe implements Runnable{
public int flag = 1;
Object o1 = new Object();
Object o2 = new Object();
public void run(){
if(flag == 1){
synchronized(o1){
try{
System.out.println("1-o1");
//Thread.sleep(500);
}catch(Exception e){
return ;
}
}
synchronized(o2){
System.out.println("2-o1");
}
}
if(flag == 0){
synchronized(o2){
try{
System.out.println("1-o2");
//Thread.sleep(500);
}catch(Exception e){
return ;
}
}
synchronized(o1){
System.out.println("2-o2");
}
}
}
public static void main(String args[]){
hehe h1 = new hehe();
hehe h2 = new hehe();
h1.flag = 1;
h2.flag = 0;
Thread t1 = new Thread();
Thread t2 = new Thread();
t1.start();
t2.start();
}
}
避免死锁的较好方法,是尽量将锁定的范围扩大,使得,要锁定的目标变少。