簡體   English   中英

Java中的多線程,等待中的困難

[英]multithreading in java,difficulty in wait

這是我的代碼的一部分,我在使用wait()時遇到問題

class Leader extends Thread {
    private Table table;
    synchronized public void run()
    {
        while(true)
        { 
            try
            {
                while(table.getResources()!=0)
                    wait();

                table.putResources(5); // here I am updating the value(I have a table class)
            } catch(InterruptedException e) { }
        }
    }
}


class Soldier extends Thread {

    public void run() 
    {
        while(true) 
        {
            try 
            {
                synchronized(this) 
                {

                    if(table.getResources()==this.need_Value)    //checking value of resource 
                    {
                        sleep(1000);
                        table.clearResources();      //this will put the value of resource to 0
                        notifyAll();
                    }
                }
            } catch(InterruptedException e) { }
        }
    }
}

所以基本上我有一個領導者類的線程和一個領導者類的線程。 最初資源為0因此在Soldier類中資源被更新為5 現在假設對於Soldier類Need_Value為5 ,那么它將資源值更新為0 因此,現在Leader類應該在資源為0再次運行,但實際上它仍在等待。 那么我的wait()有什么問題嗎?

PS-假設我有Table類以及使用的所有構造函數和變量。 我已經省略了它們,因為代碼太長

notify了另一個對象,而不是wait

Leaderthis同步( this是因為您將同步放在實例方法上)。 因此,您的Leader等待Leader實例被通知。

在您的Soldier類中,您還將與this同步,並通知該Soldier實例。

但是,由於您是在Soldier實例上進行通知的,而LeaderLeader實例上等待,因此不會收到通知。

SoldierLeader這兩個實例應使用相同的同步對象。

您可能想通過使用Leader實例作為Soldier同步對象來解決此問題

class Soldier extends Thread {

    private Leader leader;

    public Soldier(Leader leader) {
        this.leader = leader;
    }

    public void run()
    {
        while(true)
        {
            try
            {
                synchronized(leader)
                {

                    if(table.getResources()==this.need_Value)    //checking value of resource
                    {
                        sleep(1000);
                        table.clearResources();      //this will put the value of resource to 0
                        leader. notifyAll();
                    }
                }
            } catch(InterruptedException e) { }
        }
    }
}

閱讀此問題的答案: 如何在Java中使用等待和通知? 它詳細說明了如何正確使用Wait()和Notify()函數。

暫無
暫無

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

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