代码之家  ›  专栏  ›  技术社区  ›  non sequitor

为什么thread.interrupt()的作用是这样的?

  •  3
  • non sequitor  · 技术社区  · 16 年前

    这是对Java教程并发代码的修改。

    package threads;
    
    public class SimpleThreads {
     static void threadMessage(String msg) {
      String threadName = Thread.currentThread().getName();
      System.out.format("%s: %s%n", threadName,msg);
     }
     private static class MessageLoop implements Runnable{
    
      @Override
      public void run() {
       // TODO Auto-generated method stub
       String[] importantInfo= {"apple","bat","chlorine","dog","egg","fog","gun"};
       try {
        for(int i=0;i<importantInfo.length;i++) {
         Thread.sleep(4000);
         threadMessage(importantInfo[i]);
        }
       }catch(InterruptedException ie) {
        threadMessage("i wasn't done");
       }
         }
     }
     /**
      * @param args
      */
     public static void main(String[] args) throws InterruptedException{
      // TODO Auto-generated method stub
      long patience = 100;
      if(args.length > 0)
       try {
        patience = Long.parseLong(args[0]) * 1000;
       }catch(NumberFormatException nfe) {
        System.err.println("argument must be a integer");
        System.exit(1);
       }
      threadMessage("starting message loop thread");
      long startTime = System.currentTimeMillis();
      Thread t = new Thread(new MessageLoop());
      t.start();
    
      threadMessage("waiting for messageloop thread to finish");
      while(t.isAlive()) {
       threadMessage("still waiting...");
       //t.join(1000);
       if(((System.currentTimeMillis() - startTime) > patience) && t.isAlive()) {
        threadMessage("tired of waiting");
        t.interrupt();
        //t.join();
       }
      }
      threadMessage("finally");
     }
    
    }
    

    这就是输出

    main: starting message loop thread
    main: waiting for messageloop thread to finish
    main: still waiting...
    main: still waiting...
    ...(repeats about 100 times)
    main: still waiting...
    main: still waiting...
    main: still waiting...
    main: still waiting...
    main: tired of waiting
    main: still waiting...
    main: tired of waiting
    main: still waiting...
    main: tired of waiting
    main: still waiting...
    main: tired of waiting
    main: still waiting...
    main: tired of waiting
    Thread-0: i wasn't done
    main: finally
    

    我原以为在第一次之后(而且据说只有一次) main: tired of waiting 我会看到 Thread-0: i wasn't done 但是 主:厌倦了等待 出现了5次——为什么?

    2 回复  |  直到 16 年前
        1
  •  5
  •   RickNZ    16 年前

    thread.interrupt()只是向目标线程发送一个中断(信号/异常);它不会立即终止它。

    此外,在发送中断和目标线程接收和处理中断之间可能存在延迟;上下文切换不能保证是即时的。

    您可以通过执行某种形式的阻塞操作(如I/O或睡眠)或调用thread.yield()来鼓励(但不强制)JVM更快地进行上下文切换。

        2
  •  0
  •   user85421    16 年前

    Thread.interrupt() 不杀死或中断线程。
    它只是中断一些方法,如睡眠、等待、连接、中断通道上的阻塞I/O或阻塞的选择器。否则,它只设置线程的中断标志,由您来测试这个标志。
    如果删除上述代码中的睡眠,中断将没有可见的效果。

    线程将(可能)中断几次,因为实际线程(主循环)将继续运行,直到系统更改为中断的线程。中断后,您可以添加sleep()或yield()(join(),如图所示,也应该有效)以允许中断的线程运行。

        threadMessage("tired of waiting");
        t.interrupt();
        t.yield();
    

    也见 documentation of interrupt