死鎖的思路是:多線程同時(shí)被阻塞,他們中一個(gè)或者全部都在等待某個(gè)資源被被釋放.由與線程被無(wú)限期地阻塞,因此程序不可能正常終止.
public class Test4 {
public static String obj1 = "obj1";
public static String obj2 = "obj2";
public static void main(String[] args) {
sum s = new sum();
Thread thread = new Thread(s);
thread.start();
func f = new func();
Thread thread1 = new Thread(f);
thread1.start();
}
}
class sum implements Runnable{
@Override
public void run() {
try {
System.out.println("開始");
while (true) {
synchronized (Test4.obj1) {
System.out.println("鎖住obj1");
Thread.sleep(1000);
synchronized (Test4.obj2) {
System.out.println("鎖住obj2");
}
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
class func implements Runnable{
@Override
public void run() {
try {
System.out.println("開始");
while (true) {
synchronized (Test4.obj2) {
System.out.println("----鎖住obj2");
Thread.sleep(2000);
synchronized (Test4.obj1) {
System.out.println("----鎖住obj1");
}
}
}
} catch (Exception e) {
}
}
}