比如A线程和B线程 , A线程监视B线程的工作情况 , B线程用于处理某项工作,这项工作是有时间要求的,如果这项工作没有在规定时间内完成,则A线程需将B线程关闭.这该如何实现呢?

解决方案 »

  1.   

    你看这样行不?
    Thread B
    {
      private boolean runFlag = true;  public void run()
      {
        while(runFlag)
        {
          ....
        }
      }
      public void setRunFlag(boolean flag)
      {
        this.runFlag = flag;
      }
    }当Thread A 发现时间不符合条件的时候,就调用Thread B的setRunFlag(boolean flag)方法。这样Thread B就会停止。当然,你在启动Thread B的时候,让它保留一个引用在Thread A里面,这样就可以调用Thread B的方法了
    Thread A
    {
      private Thread b = null;
      
      public void register(Thread argThread)
      {
        this.b = argThread;
      }  public void run()
      {
        while(true)
        {
          if(时间不符合条件)
            b.setRunFlag(false);
        }
      }
    }
      

  2.   

    设置一个 信号变量,线程根据信号变量判断,如果要中止就在下面写return 就中止了。
    O'relliy的JAVA Thread 有详细介绍
      

  3.   

    用while(flag){}方式也不妥,因为如果在while(flag)里阻塞了的话,这个flag其实没法立即起作用啊
      

  4.   

    如果你的线程已经阻塞了的话,你可以在停的时候,把它们唤醒,当然,先把运行标志置为false,这样不就解决了这个问题吗?只是代码稍微修改一下就可以了
      

  5.   

    大家一起讨论吧,不要让这个帖子沉下去.也许这是Java的线程中断机制的缺陷啊.
      

  6.   

    public void run()
      {
        while(runFlag && !interrupted)
        {
          ....
        }
      }
    Two Methods
    1)set flag
    2)use Thread.interrupe()
      

  7.   

    public void run()
      {
        while(runFlag && !this.isInterrupted())
        {
          ....
        }
      }
    Two Methods
    1)set flag
    2)use Thread.interrupt()
      

  8.   

    Thread.interrupt()目的是不是就是为了制造一个异常,好让线程退出?
      

  9.   

    Thread.interrupt()目的是不是就是为了制造一个异常,好让线程退出?
    --------------------------------------
    Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread.
    当你的线程睡着了的时候,别人调用了interrupt(),那么就抛出异常,否则,不会抛出。所以,你需要在while循环中使用两个条件!interrupted() && more work todo。睡着的时候被中断,通过InterruptedException异常退出,工作的时候被中断则通过主动判断中断标志来退出。
      

  10.   

    有两个地方注意下就哈了。
    一是作为判断循环的条件要是同步读取,或声明为易变类型的。
    二是要interrupt一下
      

  11.   

    我也是到处在找这个问题的答案..
    想想java的ide工具, 他们调试的时候能随时中止线程...它们是怎么做到的?
    目前为止我还是只能用stop完成上面的要求.唉....