同步的本質在於:一個線程等待另一個線程執行完畢後纔可以繼續執行。但是,現在相關的幾個線程彼此之間都在等待着,那麼就會造成死鎖。
範例:死鎖
package hhh.Test;
class Pen {
private String pen = "筆" ;
public String getPen() {
return pen;
}
}
class Book {
private String book = "本" ;
public String getBook() {
return book;
}
}
public class test {
private static Pen pen=new Pen();
private static Book book=new Book();
public static void main(String[] args){
Thread threadA=new Thread(new Runnable() {
@Override
public void run() {
synchronized (pen){
System.out.println("我有筆...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (book){
System.out.println("但是我還想要本子...");
}
}
}
});
threadA.setName("threadA");
threadA.start();
Thread threadB=new Thread(new Runnable() {
@Override
public void run() {
synchronized (book){
System.out.println("我有本子...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (pen){
System.out.println("但是我還想要書...");
}
}
}
});
threadB.setName("threadB");
threadB.start();
}
}
死鎖一旦出現之後,整個程序就將中斷執行,所以死鎖屬於嚴重性問題。過多的同步會造成死鎖,對於資源的上鎖一定要注意不要成"環"。
避免死鎖:銀行家算法