java 线程 interrupt,java线程:Thread.interrupt()不起作用

I need to kill a thread that is not created in my code. In other words, the thread object is created by api (Eclipse JFace). Here is my code

ProgressMonitorDialog dialog = new ProgressMonitorDialog(null);

try {

IRunnableWithProgress rp = new IRunnableWithProgress(){

@Override

public void run(IProgressMonitor monitor)

throws InvocationTargetException, InterruptedException {

Thread.sleep(3000);

Thread t = Thread.currentThread();

t.getThreadGroup().list();

t.interrupt();

}

};

dialog.run(true, true, rp);

}

catch (Exception e) {

e.printStackTrace();

}

Thread.currentThread() returns a thread with the name "ModalContext". Line t.getThreadGroup().list() returns the following data:

...

Thread[qtp1821431-38,5,main]

Thread[qtp1821431-39,5,main]

Thread[qtp1821431-40,5,main]

Thread[qtp1821431-42 Acceptor0 SelectChannelConnector@0.0.0.0:18080,5,main]

Thread[DestroyJavaVM,5,main]

Thread[ModalContext,5,main]

Variables "dialog" and "rp" do not have reference to their runnable object. And they don't have any method to close or cancel. So I want to kill that thread "ModalContext" directly. Calling t.interrupt() does not work. Thread MoadlContext continues to run. How can I kill the thread? Thanks

解决方案

t.interrupt() does not actually interrupt the thread immediately it only update interrupt status of thread. If your thread contains method which poll the interrupt status (i.e. sleep )only then the thread will be interrupted otherwise the thread simply complete the execution and interrupt status will be ignored.

Consider following example,

class RunMe implements Runnable {

@Override

public void run() {

System.out.println("Executing :"+Thread.currentThread().getName());

for(int i = 1; i <= 5; i++) {

System.out.println("Inside loop for i = " +i);

}

System.out.println("Execution completed");

}

}

public class Interrupted {

public static void main(String[] args) {

RunMe runMe = new RunMe();

Thread t1 = new Thread(runMe);

t1.start();

t1.interrupt();//interrupt ignored

System.out.println("Interrupt method called to interrupt t1");

}

}

OUTPUT

Interrupt method called to interrupt t1

Executing :Thread-0

Inside loop for i = 1

Inside loop for i = 2

Inside loop for i = 3

Inside loop for i = 4

Inside loop for i = 5

Execution completed

Now just add Thread.sleep(200); in run and you will see the InterruptedException.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值