中断
- 通过Thread类中的interrupt()方法,给出中断信号,结束当前线程
- 通过ThreadGroup类中的interrupt()方法,给出中断信号,结束一组线程
如果线程处于阻塞状态,会抛出InterruptedException
Thread中的interrupt()方法示例代码
package test;
import java.util.logging.Logger;
public class Test {
private static final Logger log = Logger.getLogger(Test.class.getName());
public static void main(String[] args) {
Thread t = new Test().startThread("[Sub Thread]");
try {
t.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("thread " + Thread.currentThread().getName() + " send interrupt flag.");
t.interrupt();
}
public Thread startThread(String tname) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
int sum = 0;
int i = 0;
log.info("thread " + Thread.currentThread().getName() + " i is " + i);
log.info("thread " + Thread.currentThread().getName() + " sum is " + sum);
while(!Thread.currentThread().isInterrupted()) {
log.info("thread " + Thread.currentThread().getName() + " is running.");
while(sum<i*1000) {
sum++;
}
i++;
if(i > 100) {
log.info("thread " + Thread.currentThread().getName() + " is finished.");
break;
}
}
log.info("thread " + Thread.currentThread().getName() + " is stopped.");
log.info("thread " + Thread.currentThread().getName() + " i is " + i);
log.info("thread " + Thread.currentThread().getName() + " sum is " + sum);
}
}, tname);
t.start();
return t;
}
}
网友评论