2013-03-10 47 views
2

我只是即兴使用线程中断取消线程。虽然在我的代码中两个线程都停止了,但看起来我并没有赶上InterruptedException我只是想知道为什么?中断正在运行的线程

监制:

public class Producer implements Runnable{ 

    private BlockingQueue<String> queue ; 

    public Producer(BlockingQueue<String> queue) { 
     this.queue = queue; 
    } 

    @Override 
    public void run() { 
      try { 

     while (!Thread.currentThread().isInterrupted()){ 
       queue.put("Hello"); 
      } 
     }catch (InterruptedException e) { 
       System.out.println("Interupting Producer"); 
       Thread.currentThread().interrupt(); 
     } 
    } 
} 

消费者:

public class Consumer implements Runnable { 

    BlockingQueue<String> queue; 

    public Consumer(BlockingQueue<String> queue) { 
     super(); 
     this.queue = queue; 
    } 

    @Override 
    public void run() { 

     String s; 
     try { 
      while (!Thread.currentThread().isInterrupted()) { 
       s = queue.take(); 
       System.out.println(s); 
      } 
     } catch (InterruptedException e) { 
      System.out.println("Consumer Interupted"); 
      Thread.currentThread().interrupt(); 
     } 
    } 
} 

现在主营:

public static void main(String[] args) { 
    BlockingQueue<String> queue = new LinkedBlockingQueue<String>(); 

    Thread producerThread = new Thread(new Producer(queue)); 
    Thread consumerThread = new Thread(new Consumer(queue)); 
    producerThread.start(); 
    consumerThread.start(); 

    try { 
     Thread.sleep(1000); 
    } catch (InterruptedException e) { 
    } finally { 
     producerThread.interrupt(); 
     consumerThread.interrupt(); 
    } 
} 

虽然线程停下来,我不明白为什么InterruptedException不咳嗽。 它应该打印catch块内的中断消息,但没有打印

+2

这可能不应该有'Java的ee'标签... – 2013-03-10 15:22:48

+0

如何您认为?中断的线程是否可以检查状态? – 2013-03-10 15:28:30

回答

3

你有一个无界的队列,因此生产者和消费者都不会在队列上被阻塞。因此,没有可能抛出InterruptedException的操作被中断。

1

这里是连接例子中断:

公共类TestThread1实现Runnable {

public void run() { 
    while(Thread.currentThread().isInterrupted() == false) { 
     System.out.println("dans la boucle"); 

     //on simule une courte pause 

     for(int k=0; k<100000000; k++); 

     System.out.println("Thread isInterrupted = " + Thread.currentThread().isInterrupted()); 
    } 
} 

public static void main(String[] args) { 
    Thread t = new Thread(new TestThread1()); 
    t.start(); 

    //on laisse le temps à l'autre Thread de se lancer 
    try { 
     Thread.sleep(1000); 

    } catch(InterruptedException e) {} 

    System.out.println("interruption du thread"); 
    t.interrupt(); 
} 

}

执行的结果是:

丹斯拉仿羔皮呢

线程isInterrupted =假

丹斯拉仿羔皮呢

中断线程杜

线程isInterrupted =真