이것은 Lock 객체에 대한 Oracle의 Java 자습서에있는 예제입니다. 누군가 제가 코드를 올바르게 해석했는지 확인해주십시오.스레드가 잠금을 해제 한 후에도 스레드가 계속 실행되는 이유는 무엇입니까?
다른 스레드가 같은 방식으로 작동하기 때문에 첫 번째 스레드 만 고려할 것입니다.
먼저 alphonse 잠금을 획득하고 impendingBow 메소드에 액세스합니다. 이제이 메소드는 두 인스턴스의 두 개의 잠금을 스레드에 할당하려고 시도합니다. 스레드가 두 잠금을 모두 획득 할 수 없으면 획득 한 잠금을 해제합니다. 이것은 내가 갇혀있을 때입니다. 스레드가 잠금을 해제하면 다른 인스턴스는 두 인스턴스에 모두 액세스 할 수 있으며 첫 번째 스레드는 잠금을 해제 한 직후 실행을 중지해야합니다. 하지만 실제로는 그렇지 않습니다. 여전히 부울 값을 반환하고 bow 메서드에서 else 문을 계속 실행합니다. 왜 그런 일이 일어날까요? 동기화 된 코드처럼 스레드가 잠금을 다시 얻을 때까지 스레드가 실행을 멈춰야한다고 생각했습니다.
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.Random;
public class Safelock {
static class Friend {
private final String name;
private final Lock lock = new ReentrantLock();
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public boolean impendingBow(Friend bower) {
Boolean myLock = false;
Boolean yourLock = false;
try {
myLock = lock.tryLock();
yourLock = bower.lock.tryLock();
} finally {
if (! (myLock && yourLock)) {
if (myLock) {
lock.unlock();
}
if (yourLock) {
bower.lock.unlock();
}
}
}
return myLock && yourLock;
}
public void bow(Friend bower) {
if (impendingBow(bower)) {
try {
System.out.format("%s: %s has"
+ " bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
} finally {
lock.unlock();
bower.lock.unlock();
}
} else {
System.out.format("%s: %s started"
+ " to bow to me, but saw that"
+ " I was already bowing to"
+ " him.%n",
this.name, bower.getName());
}
}
public void bowBack(Friend bower) {
System.out.format("%s: %s has" +
" bowed back to me!%n",
this.name, bower.getName());
}
}
static class BowLoop implements Runnable {
private Friend bower;
private Friend bowee;
public BowLoop(Friend bower, Friend bowee) {
this.bower = bower;
this.bowee = bowee;
}
public void run() {
Random random = new Random();
for (int n = 0; n <5;n++) {
try {
Thread.sleep(Math.round(Math.random()*1000));
} catch (InterruptedException e) {}
bowee.bow(bower);
}
}
}
public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new BowLoop(alphonse, gaston)).start();
new Thread(new BowLoop(gaston, alphonse)).start();
}
}
스레드가'Lock' 객체를 해제 한 후 실행을 멈추어야한다고 생각합니까? –
lock 객체를 synchronized 코드와 관련시킵니다.이 코드는 잠금을 획득하면 스레드가 코드를 실행하도록하고, 그렇지 않으면 스레드를 차단합니다. – PMH
잠금이 실행 중이 아니면 어떻게 확보 할 수 있습니까? –