簡體   English   中英

我是否正確理解資源分配的概念?

[英]Am I understanding the concept of resource allocation correctly?

我對同步在Java中如何進行資源分配感到困惑。 當我得到以下Java代碼時:

import java.util.concurrent.Semaphore;

public class Deadlock {
public Deadlock () {
    Semaphore mutex[] = new Semaphore[4];

    for (int i = 0; i < 4; i++) 
        mutex[i] = new Semaphore(1);

    A threadA = new A(mutex);
    B threadB = new B(mutex);
    C threadC = new C(mutex);

    threadA.start();
    threadB.start();
    threadC.start();
}

private class A extends Thread {
    private Semaphore[] resource;

    public A(Semaphore[] m) {
        resource = m;
    }

    public void run() {
        System.out.println("A started");
        synchronized( resouce[1] ) {
            System.out.println("A locks rsc 1");
            synchronized (resource[0]) {
                System.out.println("A locks rsc 0");
            }
        }
        System.out.println("A finished");
    }
}
private class B extends Thread {
    private Semaphore[] resource;

    public B(Semaphore[] m) {
        resource = m;
    }

    public void run() {
        System.out.println("B started");
        synchronized( resouce[3] ) {
            System.out.println("B locks rsc 3");
            synchronized (resource[0]) {
                System.out.println("B locks rsc 0");
                synchronized (resource[2]) {
                    System.out.println("B locks rsc 2");
                }
            }
        }
        System.out.println("B finished");
    }
}
private class C extends Thread {
    private Semaphore[] resource;

    public C(Semaphore[] m) {
        resource = m;
    }

    public void run() {
        System.out.println("C started");
        synchronized( resouce[2] ) {
            System.out.println("C locks rsc 2");
            synchronized (resource[1]) {
                System.out.println("C locks rsc 1");
            }
        }
        System.out.println("C finished");
    }
}
}

據我了解,當線程A啟動時,線程A鎖定了資源1和資源0。因此,當線程B啟動時,它將獲得對資源3的鎖定,但將等待資源0從線程A釋放。線程B在資源0上沒有鎖定,將無法在資源2上等待。線程C啟動時,它將在資源2上具有鎖定,但也等待資源1從線程A釋放。

因此,當將其繪制為資源分配圖時,它將如下所示: 在此處輸入圖片說明

這里,從P到R的節點是指對資源的請求處理。 從R到P的節點表示該進程已鎖定資源。

我理解正確嗎? 歡迎任何幫助。 謝謝。

線程B啟動時,它將獲取對資源3的鎖定,但將等待資源0從線程A釋放

嗯,但是假設A仍在運行。 它可能已經完成,甚至可能還沒有開始。 達到死鎖狀態的機會可能僅發生於運行的千分之一中。 這就是線程異步並發運行的本質。 很難預測它們的精確行為。

另外,通過調用也正在同步的System.out.println(...)使事情變得復雜。 這將引發您的測試並改變比賽條件。

我理解正確嗎?

我認為您正在適當地理解資源圖,而不是在正確的時間達到完美的死鎖點有多困難。

要嘗試的一件事是在while(true)循環中執行以下操作。

while (true) {
   A threadA = new A(mutex);
   B threadB = new B(mutex);
   C threadC = new C(mutex);
   threadA.start();
   threadB.start();
   threadC.start();
   threadA.join();
   threadB.join();
   threadC.join();
}

在某個時候,輸出將停止,CPU將變為0,您將知道它已經達到死鎖狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM