자바 스레드 (동기화 및 잠금)에 대해 배우고 있었지만 어떻게 든이 두 가지의 차이점을 찾을 수 없었습니다.스레드 인스턴스 새롭고 오래된 자바
// 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
우리가 runnable 타겟을 Thread 클래스에 넘길 때 어떤 차이가 있는지 설명 할 수있다. 1. 동일한 인스턴스 2. 다른 인스턴스
와우. 그것은 모든 것을 설명합니다. 나는 obj가 Thread A의 자물쇠를 획득한다고 생각하고 혼란 스러웠다. 귀하의 의견에 감사드립니다. –
도움이 된 것을 알면 다행입니다. – Kshitij