经典的死锁例子,在以后的编程中可以将不确定是否死锁的程序加上超时判断。
import java.util.concurrent.*;
public class DeadLock implements Runnable {
public int flag = 1;
//静态对象是类的所有对象共享的
private static Object o1 = new Object(), o2 = new Object();
@Override
public void run() {
System.out.println("flag=" + flag);
if (flag == 1) {
synchronized (o1) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (o2) {
System.out.println("1");
}
}
}
if (flag == 0) {
synchronized (o2) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (o1) {
System.out.println("0");
}
}
}
}
public static void main(String[] args) {
DeadLock td1 = new DeadLock();
DeadLock td2 = new DeadLock();
td1.flag = 1;
td2.flag = 0;
//td1,td2都处于可执行状态,但JVM线程调度先执行哪个线程是不确定的。
//td2的run()可能在td1的run()之前运行
final ExecutorService exec = Executors.newFixedThreadPool(1);
Callable<String> call = new Callable<String>() {
public String call() throws Exception {
Thread t1=new Thread(td1);
Thread t2=new Thread(td2);
t1.start();
t2.start();
t1.join();
return "线程执行完成.";
}
};
Future<String> future = exec.submit(call);
String obj = null; //任务处理超时时间设为 1 秒
try {
obj = future.get(1000 * 5, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
// e.printStackTrace();
System.out.println("线程锁死,执行超时" );
}
System.out.println("任务成功返回:" + obj);
}
}