转自:http://andyzhu.blog.51cto.com/4386758/848946
在Java中有专门终止某个线程的API,如stop()和interrupt()。其中stop()由于安全机制的我问题已经被废弃不用,现在就剩下interrupt。其实这个方法并不是一个终断动作的操作,而是一个设置终断状态的操作。它需要和isInterrupted()配合使用。例如:
- package org.leadfar;
- public class MyThread04 extends Thread {
- private boolean stop = false;
- public MyThread04(String threadName) {
- super(threadName);
- }
- @Override
- public void run() {
- for (int j = 0; j < 100; j++) {
- if(this.isInterrupted()) break;
- System.out.println(Thread.currentThread().getName()+":"+j);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- public void setStop() {
- this.stop = true;
- }
- //第一个线程
- public static void main(String[] args) {
- MyThread04 t = new MyThread04("辅线程");
- t.start();
- for (int i = 0; i < 10; i++) {
- System.out.println(Thread.currentThread().getName()+":"+i);
- }
- System.out.println("....................");
- t.interrupt();
- }
- }
但这个很可能不会终止线程,因为当我们终止这个线程时很可能就会发生InterruptedException异常,当有这个异常发生时我们设置的终断状态也会被清除,所以我们要终断某个线程应采用以下这个方法:
- package org.leadfar;
- public class MyThread04 extends Thread {
- private boolean stop = false;
- public MyThread04(String threadName) {
- super(threadName);
- }
- @Override
- public void run() {
- for (int j = 0; j < 100; j++) {
- if(stop) break;
- System.out.println(Thread.currentThread().getName()+":"+j);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- public void setStop() {
- this.stop = true;
- }
- //第一个线程
- public static void main(String[] args) {
- MyThread04 t = new MyThread04("辅线程");
- t.start();
- for (int i = 0; i < 10; i++) {
- System.out.println(Thread.currentThread().getName()+":"+i);
- }
- System.out.println("....................");
- t.setStop();
- }
- }
通过设置一个我们自己的标识来达到终端某个线程。