繁体   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