我正在學習java線程(同步和鎖),但不知何故,我無法找到這兩件事之間的區別。線程實例新老java
// Two different instances of SyncExample
Thread a1 = new Thread(new SyncExample(), "A");
Thread b1 = new Thread(new SyncExample(), "B");
// Same instance is passed to both the threads
SyncExample syn = new SyncExample();
Thread a2 = new Thread(syn, "A");
Thread b2 = new Thread(syn, "B");
// I believe in total 4 stacks are built.
a1.start();
b1.start();
a2.start();
b2.start();
public class SyncExample implements Runnable {
Object obj = new Object();
@Override
public void run() {
this.myName();
}
private void myName() {
synchronized (obj) {
System.out.print("Define" + Thread.currentThread().getName());
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
System.out.println(ex);
}
System.out.print("tly" + Thread.currentThread().getName());
}
System.out.println(" Maybe" + Thread.currentThread().getName());
}
}
public class SyncExample implements Runnable {
Object obj = new Object();
@Override
public void run() {
this.myName();
}
private void myName() {
synchronized (obj) {
System.out.print("Define" + Thread.currentThread().getName());
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
System.out.println(ex);
}
System.out.print("tly" + Thread.currentThread().getName());
}
System.out.println(" Maybe" + Thread.currentThread().getName());
}
}
但這裏的問題是,當我運行使用
1該實施例中 - 相同的參考輸出是:
DefineAtlyA MaybeA
DefineBtlyB MaybeB
2 - 2的不同實例:
DefineADefineBtlyAtlyB MaybeB
MaybeA
當我們將可運行目標傳遞給線程類時,可以解釋我有什麼不同嗎?1.同一個實例 2.不同實例
哇。這解釋了一切。我很困惑,一直認爲obj獲得了線程A的鎖定,事實上它恰恰相反。謝謝你的評論。 – 2013-03-05 04:29:40
很高興知道它有幫助。 – Kshitij 2013-03-06 06:37:48