我正在学习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