【问题标题】:why i am getting error while implementingInterThread Communication in java using wait and notify?为什么我在使用等待和通知在java中实现InterThread通信时出错?
【发布时间】:2015-04-06 13:10:40
【问题描述】:

我正在实现一个简单的 SimpleInterThreadCommunication 示例,并使用了等待和通知。

我在 InterThread 类中得到一个错误,谁能解释原因

public class InterThread 

{

public static void main(String s[])throws InterruptedException

{

    Thread b=new Thread();

    b.start();

    Thread.sleep(10);

    synchronized (b) 

    {

    System.out.println("Main thread trying to call wait");

    b.wait();

    System.out.println("Main thread got notifies");

    System.out.println(b.total); //error here total cannot be resolved to a field

   }

 }

}

class ThreadB extends InterThread

{

    int total=0;

    public void run()

    {

        synchronized(this)

        {

            System.out.println("child thread got notifies");

            for(int i=0;i<3;i++)

            {

                total=total+i;

            }

            System.out.println("child thread ready to give  notification");

              this.notify();
        }

    }

}

【问题讨论】:

  • 这是因为您的对象 b 属于线程类,并且总字段未在线程类中隐式定义,而是您在 ThreadB 类中定义了变量 b。因此它无法解析为变量。
  • 因为Thread 没有名为bpublic 字段。
  • 顺便说一句。使用 java.util.concurrent 中的类可以以更简单、更可靠的方式完成线程通信。例如LinkedTransferQueue

标签: java multithreading wait notify


【解决方案1】:

您需要创建ThreadB 类的对象,然后您才能访问总计字段。 Thread 类对象看不到它。

您已创建 Thread 类的 b 对象,并且在 Thread 类中没有任何名为 total 的此类字段可用。

改变你的代码如下:

    ThreadB b1=new ThreadB();
    System.out.println(b1.total);

【讨论】:

  • 为什么我现在没有得到总输出我的输出:子线程得到通知子线程准备发出通知主线程试图调用等待
  • 您需要更改通知和等待的顺序。您首先调用通知,然后等待,反之亦然。因为如果一个线程正在等待,那么其他线程应该通知它。如果没有其他线程会调用通知,那么您的线程可能会永远等待,这就是为什么在调用 wait() 之后什么都没有发生
【解决方案2】:

在乐于助人的人的建议下回答我做出了改变 这是更正后的代码

公共类InterThread

{

public static void main(String s[])throw InterruptedException

{

ThreadB b=new ThreadB(); //correction 1

b.start();

Thread.sleep(10);

synchronized (b) 

{

  System.out.println("Main thread trying to call wait");

  b.notify();  //correction2

  System.out.println("Main thread got notifies");

System.out.println(b.total); 

}

}

}

类 ThreadB 扩展了 InterThread

{

int total=0;

public void run()

{

    synchronized(this)

    {

        System.out.println("child thread got notifies");

        for(int i=0;i<3;i++)

        {

            total=total+i;

        }

        System.out.println("child thread ready to give  notification");

    try

       {

        System.out.println("child thread ready trying to call wait");

        this.wait(); //corrected 3

       }

        catch(InterruptedException e)

        {

            System.out.println("interrupted Exception");

        }

   }

}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-06
    • 2022-01-10
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多