为什么我在 java 中使用等待和通知实现线程间通信时出错?

why i am getting error while implementingInterThread Communication in java using wait and notify?

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

我在 InterThread 中收到总计错误 class 谁能解释为什么

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();
        }

    }

}

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

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

像下面这样更改您的代码:

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

回答我根据有帮助的人的建议进行了更改 这是更正后的代码

public class InterThread

{

public static void main(String s[])throws 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); 

}

}

}

class 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");

        }

   }

}

}