Java或者Android開發(fā)中經(jīng)常要中斷線程,這里總結(jié)下中斷正在運行的線程
方法一:
設(shè)置標(biāo)記位置flag
public class InterruptThreadTest {
public static void main(String[] args) {
InterruptThread t=new InterruptThread();
t.start();
try {
Thread.sleep(5000);
t.flag=false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class InterruptThread extends Thread{
public boolean flag=true;
@Override
public void run() {
super.run();
while (flag){
System.out.println("run.....");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
方法二:
使用java提供的中斷的方法interrupt()
/**
* <描述>
*
* @author levi
* @email lilinwei@xiaoyouzi.com
* @date: 2018/3/7
* @version: v1.0
*/
public class InterruptThreadTest2 {
public static void main(String[] args) {
InterruptThread t=new InterruptThread();
t.start();
try {
Thread.sleep(5000);
t.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class InterruptThread extends Thread{
@Override
public void run() {
super.run();
while (true){
System.out.println("run.....");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException.....");
e.printStackTrace();
break;//線程異常中斷線程
}
}
}
}
}
方法三:利用守護線程
既在創(chuàng)建線程中創(chuàng)建一個守護線程,如果創(chuàng)建線程結(jié)束則守護線程也。方法三的使用場景模式,如:一個線程正在拷貝一個很大的文件或者正在網(wǎng)絡(luò)請求,結(jié)束而且耗時超出預(yù)期,這時候又想中斷它。如果使用方法一&方法二已經(jīng)不起使用了。這時候就可以使用方法三:
/**
* <描述>
*
* @author levi
* @email lilinwei@xiaoyouzi.com
* @date: 2018/3/7
* @version: v1.0
*/
public class InterruptThreadTest3 {
public static void main(String[] args) {
InterruptThreadTest3 InterruptThread=new InterruptThreadTest3();
long startTime=System.currentTimeMillis();
InterruptThread.execute(()->{
try {
System.out.println("在操作一個很大很大的文件....");
Thread.sleep(50_000);
} catch (InterruptedException e) {
System.out.println("守護線程結(jié)束....");
e.printStackTrace();
}
});
InterruptThread.shutDown(5_000);
long endTime=System.currentTimeMillis();
//在統(tǒng)計線程工作時間時,可能會比實際使用的時間長一些,因為在new,start的過程中消耗了一些時間
System.out.println("工作了...>"+(endTime-startTime));
}
public Thread serviceThread;
public boolean finished=false;
public void execute(Runnable task){
serviceThread=new Thread(()->{
Thread wokerTask=new Thread(task);
wokerTask.setDaemon(true);
wokerTask.start();
try {
wokerTask.join();//此線程等待子線程執(zhí)行完時才退出
finished=true;
} catch (InterruptedException e) {
System.out.println("創(chuàng)建線程中斷(結(jié)束)");
}
});
serviceThread.start();
}
//設(shè)置超時時間
public void shutDown(long minlls){
long currentTime=System.currentTimeMillis();
while (!finished){//標(biāo)記線程還沒結(jié)束
if(System.currentTimeMillis()-currentTime>minlls){
//超時了結(jié)束線程
serviceThread.interrupt();
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;//中斷當(dāng)前監(jiān)控線程
}
}
}
}