java - 多线程状态相关问题

标签 java multithreading concurrency

我得到了以下代码片段:

public class ThreadTest{

  private static class Thread01 extends Thread{
    private Thread02 _th2; 
    public int foo = 0;

    public void setThrd02(Thread02 thrd2){
       _th2 = thrd2;
    }

    public void run(){
      try{
        for(int i=0;i<10;i++) foo += i;

        synchronized(this){this.notify();};

        synchronized(_th2){_th2.wait();};

        System.out.print(" Foo: " + _th2.foo);
      }catch(InterruptedException ie){ ie.printStackTrace();}    
    }
  }

  private static class Thread02 extends Thread{

    private final Thread01 _th1;
    public int foo = 0;

    public Thread02(Thread01 th1){
      _th1 = th1;
    }

    public void Run(){
       try{
         synchronized(_th1){_th1.wait();}
         foo = _th1.foo;

         for(int i=0;i<10;i++) foo += i;
         synchronized(this){this.notify();};
           }
       catch(InterruptedException ie){ie.printStackTrace();}

    }

  }

  public static void main(){
    Thread01 th1 = new Thread01();
    Thread02 th2 = new Thread02(th1);

    th1.setThrd02(th2);

    th1.start(); th2.start();
    th1.join(); th2.join();
  } 
}

我认为代码的假设和相应的目的就像 th2先运行,通过调用_th1.wait()改变为等待状态; 然后,th1计算foo并唤醒th2,th1进入等待状态; Th2从thread1读取foo并更新为110,然后唤醒th1,th2退出。 然后th1退出。

线程可能会非常危险,因为线程 1 很可能先运行而线程 2 将永远等待。

我不确定代码是否还有其他潜在问题。

解决问题的一种可能方法是,例如在 thread1 中

公共(public)类 ThreadTest{

private static boolean updated = false; private static boolean finished = false;

私有(private)静态 Thread01 扩展线程{

公共(public)无效运行(){ //进行计算 而(完成){ 等待(); } //输出结果 }

私有(private)静态 Thread02 扩展线程{ 公共(public)无效运行(){

同时(假){ 等待();

foo = th1.foo; //进行计算 //通知线程 1 的类似机制 }

最佳答案

无法保证您的线程中的顺序。 Thread01过去就够了 synchronized(this){this.notify();}; 在 Thread02 执行 synchronized(_th1){_th1.wait();} 让两个线程无限期等待之前。

注意:您在 _th1 和 _th2 上调用 waitnotify 的事实无关紧要。这里的线程将被视为任何其他对象。

关于java - 多线程状态相关问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6498982/

相关文章:

java - 是否可以将 CSV 行解析为具有正确值类型的 JsonNodes

java - SWT TableViewer 摘要行

c++ - 多线程编程如何保证执行顺序?

java - JDK 1.6 和 JDK 1.7 中 ConcurrentHashMap 的不同 `next` 条目

c++ - 如何在 C++ 中同时写入和读取文件

java - starttls+smtp 与 SMTP over SSL 是否相同?

java - 为 androidTest sourceSet 配置 res srcDirs

c - 如何判断线程是否响应唤醒调用?

c# - .NET:由于字典,HttpClient 中的 CPU 使用率为 100%?

multithreading - 为什么这个变量定义意味着静态生命周期?