Concurrency – 7

      在〈Concurrency – 7〉中尚無留言

Q001

NO.41 Given
public class Foo {
    private final ReentrantLock lock = new ReentrantLock();
    private State state;
    public void foo() throws Exception {
        try {
            lock.lock();
            state.mutate();
        }
        finally {
            lock.unlock();
        }
    }
}

What is required to make the Foo class thread safe?
A. No change is required.
B. Make the declaration of lock static.
C. Replace the lock constructor call with new ReentrantLock (true).
D. Move the declaration of lock inside the foo method.


Answer : A

Reentrant[riˈen.trənt] 可重入的,ReentrantLock 是 Java 的一種鎖機制,比 synchronized 更靈活的控制,常見於需手動鎖定、解鎖。這是撰寫安全執行緒的方法。

lock.lock() 一定要寫在 try-catch 中,而 lock.unlock() 一定要寫在 finally 中。

Q002

NO.82 And the code fragment:
Resource resource = new Resource();
Worker worker = new Worker();
Thread t1 = new Thread(() -> resource.processWork(worker));
Thread t2 = new Thread(() -> worker.consumeResource(resource));
t1.start();
t2.start();

Which situation will occur on code fragment execution?
A. Livelock
B. Deadlock
C. Race Condition
D. Starvation


Answer: D

Livelock 是執行緒不阻塞,但不斷重試或讓步。

Deadlock 是死結,執行緒 A 鎖住 R1 等 R2,執行緒 B 鎖住 R2 等待 R1。

Starvation 是飢餓的意思。

此題有點爭議。網路上說是 Starvation。ChatGPT 則說是 Deadlock。

🔒 更多內容,請登入會員繼續閱讀。

立即登入

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *