我正在学习 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. 不同实例时有什么不同