是不是應該等到同步對象解鎖?
該鎖由線程舉行,讓你同步在兩次(在main
第一次調用doSomething
的情況下)沒有關係的事實,這是相同的線程上。如果另一個線程然後嘗試在objToSync
進入塊,即其他線程會等到這個線程釋放所有的鎖。
您的代碼將做到這一點:
- 輸入
main
- 獲取當前線程鎖
objToSync
對象
- 輸出 「的東西一個」
- 呼叫
doSomething
- 得到一個當前線程的第二個鎖
objToSync
- 輸出「東西兩個」
- 釋放第二鎖在當前線程上
objToSync
- 返回從
doSomething
- 輸出「東西三」
- 發佈第一鎖定爲當前線程上
objToSync
- 呼叫
doSomething
- 上
objToSync
- 輸出「的東西兩個」
獲取新的鎖(對於同一個線程)
- 釋放,從
doSomething
- 返回鎖定
- 返回從
main
下面是一個使用兩個線程的例子:
public class SyncExample {
private static Object objToSync = new Object();
public static final void main(String[] args) {
Thread second;
System.out.println("Main thread acquiring lock");
synchronized (objToSync) {
System.out.println("Main thread has lock, spawning second thread");
second = new Thread(new MyRunnable());
second.start();
System.out.println("Main thread has started second thread, sleeping a moment");
try {
Thread.currentThread().sleep(250);
}
catch (Exception e) {
}
System.out.println("Main thread releasing lock");
}
System.out.println("Main thread sleeping again");
try {
Thread.currentThread().sleep(250);
}
catch (Exception e) {
}
System.out.println("Main thread waiting for second thread to complete");
try {
second.join();
}
catch (Exception e) {
}
System.out.println("Main thread exiting");
}
static class MyRunnable implements Runnable {
public void run() {
System.out.println("Second thread running, acquiring lock");
synchronized (objToSync) {
System.out.println("Second thread has lock, sleeping a moment");
try {
Thread.currentThread().sleep(250);
}
catch (Exception e) {
}
System.out.println("Second thread releasing lock");
}
System.out.println("Second thread is done");
}
}
}
輸出:
Main thread acquiring lock
Main thread has lock, spawning second thread
Main thread has started second thread, sleeping a moment
Second thread running, acquiring lock
Main thread releasing lock
Main thread sleeping again
Second thread has lock, sleeping a moment
Main thread waiting for second thread to complete
Second thread releasing lock
Second thread is done
Main thread exiting
*「爲什麼main中的doSomething被調用?」*有兩個調用'main'中的'doSomething',你指的是哪一個? –
同步對象塊中的一個 – Madz