在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();
- }
- }
通過設置一個我們自己的標識來達到終端某個線程。