当一个类中,有两个synchronized方法,其中一个方法是一个死循环,当多个线程调用类中的不同方法时,会造成死锁,解决方法是把synchronized方法转换成在方法中加synchronized语句块,而且两个方法持有不同的对象,这就解决了死锁问题,当多个线程调用不同方法时,虽然一个线程出现死锁,但不影响其他应用调用另一个方法。
Task
public class Task {
Object o1 = new Object();
public void doLongTask() {
synchronized (o1) {
System.out.println("a start");
boolean a = true;
while (a){
}
System.out.println("a end");
}
}
Object o2 = new Object();
public void doIntTask(){
synchronized (o2){
System.out.println("b start");
System.out.println("b end");
}
}
}
Thread1
public class Thread1 extends Thread {
private Task task;
public Thread1(Task task){
this.task = task;
}
@Override
public void run() {
super.run();
task.doIntTask();
}
}
Thread2
public class Thread2 extends Thread {
private Task task;
public Thread2(Task task){
this.task = task;
}
@Override
public void run() {
super.run();
task.doLongTask();
}
}
Run
public class Run {
public static void main(String[] args){
Task t = new Task();
Thread1 t1 = new Thread1(t);
t1.start();
Thread2 t2 = new Thread2(t);
t2.start();
}
}
运行结果:
a start
b start
b end