停止現成的方式
線程停止的方式:
- 線程執行完畢,自然會停止
- 異常退出
- 設置了標誌位,當標誌位爲false時退出
- 線程中斷退出
(這也是一道常見面試題)
線程函數執行完畢正常退出和發生異常被迫退出都不受我們控制,下面討論控制線程停止的方式。
設置退出標誌位
package com.sync.demo;
import javax.swing.text.html.HTML.Tag;
public class Demo5 {
public static void main(String[] args) {
ThreadC c = new ThreadC();
Thread thread = new Thread(c);
thread.start();
try {
Thread.sleep(3000);
c.setTag(false);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class ThreadC implements Runnable{
private boolean Tag = true;
public boolean isTag() {
return Tag;
}
public void setTag(boolean tag) {
Tag = tag;
}
public ThreadC() {
super();
}
@Override
public void run() {
while (true) {
if (!Tag) {
System.out.println("=========退出============");
return ;
}else {
System.out.println("=========run============");
}
}
}
}
}
線程中斷
java提供了線程中斷機制,可以利用線程中斷機制來結束線程,運行過程中檢查線程是否被中斷或者捕獲InterruptedException異常。
判斷中斷的兩種方式:
Thread.interrupted(); 可以設置中斷的值爲false
isInterrupted()
檢查中斷:
public class Demo5 {
public static void main(String[] args) {
ThreadD threadD = new ThreadD();
threadD.start();
try {
Thread.sleep(3000);
threadD.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class ThreadD extends Thread{
public ThreadD() {
super();
}
@Override
public void run() {
while (true) {
if (isInterrupted()) {
System.out.println("=========退出============");
return ;
}else {
System.out.println("=========run============");
}
}
}
}
}
利用捕獲中斷停止線程:
public class Demo5 {
public static void main(String[] args) {
ThreadE threadE = new ThreadE();
threadE.start();
try {
Thread.sleep(3000);
threadE.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class ThreadE extends Thread {
public ThreadE() {
super();
}
@Override
public void run() {
try {
test1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void test1() throws InterruptedException {
while (true) {
if (!isInterrupted()) {
System.out.println("=========run============");
} else {
throw new InterruptedException();
}
}
}
}
}