多线程状态相关问题

2023-12-09

我得到了以下代码片段:

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 中

公共类线程测试{

私有静态布尔更新= false; 私有静态布尔完成= false;

私有静态Thread01扩展Thread{

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

私有静态Thread02扩展Thread{ 公共无效运行(){

而(假){ 等待(); }

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


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

注意:您正在打电话的事实wait and notify_th1 和 _th2 无关。这里的线程将被视为任何其他对象。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

多线程状态相关问题 的相关文章

随机推荐