能停止的线程_在沉睡中停止
1.先sleep再用interrupt()停止
实现代码如下:
自定义线程类
package com.thread6;
public class MyThread extends Thread {
@Override
public void run() {
super.run();
try {
System.out.println("run begin");
Thread.sleep(200000);
System.out.println("run end");
} catch (InterruptedException e) {
System.out.println("在沉睡中停止!进入catch!" + this.isInterrupted());
e.printStackTrace();
}
}
}
启动类
package com.thread6;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class Run {
public static void main(String[] args) {
File f = new File("out.txt");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PrintStream printStream = new PrintStream(fileOutputStream);
System.setOut(printStream);
try {
MyThread myThread = new MyThread();
myThread.start();
Thread.sleep(200);
myThread.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end!!");
}
}
执行结果
run begin
end!!
在沉睡中停止!进入catch!false
结论
从打印结果看,如果在sleep状态下停止某一线程,会进入catch语句,并且清楚停止状态值,使之变为false。
2.先interrupt()停止再sleep
上一个demo是先sleep然后再用interrupt()停止,与之相反的操作也要进行注意。
自定义线程类
package com.thread6;
public class MyThread extends Thread {
@Override
public void run() {
super.run();
try {
for (int i = 0; i < 100000; i++) {
System.out.println("i=" + (i + 1));
}
System.out.println("run begin");
Thread.sleep(200000);
System.out.println("run end");
} catch (InterruptedException e) {
System.out.println("在沉睡中停止!进入catch!" + this.isInterrupted());
e.printStackTrace();
}
}
}
启动类
package com.fiberhome.thread6;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class Run {
public static void main(String[] args) {
File f = new File("out.txt");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PrintStream printStream = new PrintStream(fileOutputStream);
System.setOut(printStream);
//开启线程
MyThread myThread = new MyThread();
myThread.start();
myThread.interrupt();
System.out.println("end!!");
}
}
执行结果
i=99985
i=99986
i=99987
i=99988
i=99989
i=99990
i=99991
i=99992
i=99993
i=99994
i=99995
i=99996
i=99997
i=99998
i=99999
i=100000
run begin
在沉睡中停止!进入catch!false