结束线程
线程的状态
- 新建(new):线程被创建时短暂处于该状态,字后调度器将把线程转变为就绪状态或阻塞状态。
- 就绪(Runnable):只要调度器把时间片分给线程,线程就可以运行。
- 阻塞(Blocked):线程能够运行,但是有条件阻止它运行。
- 死亡(Dead):通常是run()方法返回
进入阻塞状态
- 调用sleep
- 调用wait
- 等待输入/输出完成
- 视图调用同步方法
通用方法
通常可以在线程的while循环中设置一个布尔值的标志位来控制线程是否需要关闭,当需要关闭时将该标志位设为true即可退出循环,从而关闭线程。如下例所示:
package com.alpha.concurrent.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class Task implements Runnable {
private volatile static boolean canceled = false;
private static int taskId = 0;
private int id = taskId++;
@Override
public void run() {
while (!canceled) {
System.out.println(this + "running");
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(this + "canceled");
}
public static void cancel() {
canceled = true;
}
@Override
public String toString() {
return "task " + id + ":";
}
}
public class StopThread {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
exec.execute(new Task());
}
try {
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Task.cancel();
try {
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
exec.shutdown();
}
}
运行结果如下:
D:\software\java\jdk\bin\java.exe "-javaagent:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.3.6\lib\idea_rt.jar=1749:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.3.6\bin" -Dfile.encoding=UTF-8 -classpath D:\software\java\jdk\jre\lib\charsets.jar;D:\software\java\jdk\jre\lib\deploy.jar;D:\software\java\jdk\jre\lib\ext\access-bridge-64.jar;D:\software\java\jdk\jre\lib\ext\cldrdata.jar;D:\software\java\jdk\jre\lib\ext\dnsns.jar;D:\software\java\jdk\jre\lib\ext\jaccess.jar;D:\software\java\jdk\jre\lib\ext\jfxrt.jar;D:\software\java\jdk\jre\lib\ext\localedata.jar;D:\software\java\jdk\jre\lib\ext\nashorn.jar;D:\software\java\jdk\jre\lib\ext\sunec.jar;D:\software\java\jdk\jre\lib\ext\sunjce_provider.jar;D:\software\java\jdk\jre\lib\ext\sunmscapi.jar;D:\software\java\jdk\jre\lib\ext\sunpkcs11.jar;D:\software\java\jdk\jre\lib\ext\zipfs.jar;D:\software\java\jdk\jre\lib\javaws.jar;D:\software\java\jdk\jre\lib\jce.jar;D:\software\java\jdk\jre\lib\jfr.jar;D:\software\java\jdk\jre\lib\jfxswt.jar;D:\software\java\jdk\jre\lib\jsse.jar;D:\software\java\jdk\jre\lib\management-agent.jar;D:\software\java\jdk\jre\lib\plugin.jar;D:\software\java\jdk\jre\lib\resources.jar;D:\software\java\jdk\jre\lib\rt.jar;E:\WorkSpace\JAVA\IDEA\concurrent\out\production\concurrent com.alpha.concurrent.test.StopThread
task 0:running
task 1:running
task 2:running
task 3:running
task 4:running
task 3:running
task 4:running
task 1:running
task 2:running
task 0:running
task 0:running
task 2:running
task 1:running
task 4:running
task 3:running
task 3:running
task 1:running
task 4:running
task 2:running
task 0:running
task 1:running
task 3:running
task 4:running
task 2:running
task 0:running
task 0:running
task 2:running
task 4:running
task 1:running
task 3:running
task 0:running
task 2:running
task 4:running
task 1:running
task 3:running
task 2:running
task 4:running
task 0:running
task 1:running
task 3:running
task 3:running
task 1:running
task 2:running
task 0:running
task 4:running
task 0:running
task 1:running
task 2:running
task 4:running
task 3:running
task 1:canceled
task 2:canceled
task 4:canceled
task 0:canceled
task 3:canceled
Process finished with exit code 0
结束阻塞状态的线程
通常情况下可以使用上例所示的方法来终结线程,但是如果线程内部被阻塞的话,只能等线程恢复运行之后才能停止线程,比如上例中只能等sleep过后才能终结线程。但是有时阻塞的时间较长,我们希望立即结束线程,这是就需要了解中断。
中断
Thread类包含interrupt()方法,可以使用它来终止被阻塞的任务,该方法将设置线程的中断状态。如果一个线程已经被阻塞,或者视图执行一个阻塞操作,那么设置这个线程的中断状态将抛出InterruptedException。当抛出该异常或者该线程调用Thread.interrupted()时,中断状态将被复位。Thread.interrupted()提供了离开run()循环而不抛出异常的第二种方式。
在Executor上调用shutdownNow(),它将发送一个interrupt()调用给它启动的所有线程。如果只希望中断Executor启动的某一个任务,可以使用submit()启动任务,从而获得一个Future<?>对象,可以在Future对象上调用cancel方法,传递true给它来中断任务。如下例:
package com.alpha.concurrent.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
class SleepBlocked implements Runnable {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("exit from sleep");
}
}
class IOBlocked implements Runnable {
private InputStream in;
public IOBlocked(InputStream in) {
this.in = in;
}
@Override
public void run() {
try {
System.out.println("reading...");
in.read();
} catch (IOException e) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("interrupted form blocked I/O");
} else {
throw new RuntimeException(e);
}
}
System.out.println("exit from reading.");
}
}
class SynchronizedBlocked implements Runnable {
public SynchronizedBlocked() {
new Thread() {
@Override
public void run() {
f();
}
}.start();
}
public synchronized void f() {
while (true) {
Thread.yield();
}
}
@Override
public void run() {
System.out.println("Trying to call f()");
f();
System.out.println("exit from synchronized.");
}
}
public class Interrupting {
private static ExecutorService exec = Executors.newCachedThreadPool();
static void test(Runnable r) throws InterruptedException {
Future<?> f = exec.submit(r);
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("Interrupting " + r.getClass().getSimpleName());
f.cancel(true);
System.out.println("Interrupt sent to " + r.getClass().getSimpleName());
}
public static void main(String[] args) throws Exception {
test(new SleepBlocked());
test(new IOBlocked(System.in));
test(new SynchronizedBlocked());
TimeUnit.SECONDS.sleep(4);
System.out.println("Aborting with System.exit(0)");
System.exit(0);
}
}
运行结果如下
D:\software\java\jdk\bin\java.exe "-javaagent:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.3.6\lib\idea_rt.jar=1722:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.3.6\bin" -Dfile.encoding=UTF-8 -classpath D:\software\java\jdk\jre\lib\charsets.jar;D:\software\java\jdk\jre\lib\deploy.jar;D:\software\java\jdk\jre\lib\ext\access-bridge-64.jar;D:\software\java\jdk\jre\lib\ext\cldrdata.jar;D:\software\java\jdk\jre\lib\ext\dnsns.jar;D:\software\java\jdk\jre\lib\ext\jaccess.jar;D:\software\java\jdk\jre\lib\ext\jfxrt.jar;D:\software\java\jdk\jre\lib\ext\localedata.jar;D:\software\java\jdk\jre\lib\ext\nashorn.jar;D:\software\java\jdk\jre\lib\ext\sunec.jar;D:\software\java\jdk\jre\lib\ext\sunjce_provider.jar;D:\software\java\jdk\jre\lib\ext\sunmscapi.jar;D:\software\java\jdk\jre\lib\ext\sunpkcs11.jar;D:\software\java\jdk\jre\lib\ext\zipfs.jar;D:\software\java\jdk\jre\lib\javaws.jar;D:\software\java\jdk\jre\lib\jce.jar;D:\software\java\jdk\jre\lib\jfr.jar;D:\software\java\jdk\jre\lib\jfxswt.jar;D:\software\java\jdk\jre\lib\jsse.jar;D:\software\java\jdk\jre\lib\management-agent.jar;D:\software\java\jdk\jre\lib\plugin.jar;D:\software\java\jdk\jre\lib\resources.jar;D:\software\java\jdk\jre\lib\rt.jar;E:\WorkSpace\JAVA\IDEA\concurrent\out\production\concurrent com.alpha.concurrent.test.Interrupting
Interrupting SleepBlocked
Interrupt sent to SleepBlocked
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Thread.java:340)
at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
at com.alpha.concurrent.test.SleepBlocked.run(Interrupting.java:14)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
exit from sleep
reading...
Interrupting IOBlocked
Interrupt sent to IOBlocked
Trying to call f()
Interrupting SynchronizedBlocked
Interrupt sent to SynchronizedBlocked
Aborting with System.exit(0)
Process finished with exit code 0
可以看出,由sleep造成阻塞的线程被成功的唤醒,而由IO及同步锁造成的阻塞并没有被唤醒。因此可以知道,我们可以中断由sleep造成的阻塞,但是不能中断由于IO操作或者同步锁所造成的阻塞。
I/O阻塞
但是对于后两者所造成的阻塞该怎么办呢?对于I/O操作造成的阻塞,我们可以通过关闭发生阻塞的底层资源:
package com.alpha.concurrent.test;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class CloseResource {
public static void main(String[] args) throws Exception {
ExecutorService exec = Executors.newCachedThreadPool();
ServerSocket server = new ServerSocket(8080);
InputStream socketInput = new Socket("localhost", 8080).getInputStream();
exec.execute(new IOBlocked(socketInput));
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("shutdown all thread");
exec.shutdownNow();
TimeUnit.SECONDS.sleep(1);
System.out.println("close socket input");
socketInput.close();
}
}
输出结果如下:
D:\software\java\jdk\bin\java.exe "-javaagent:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.3.6\lib\idea_rt.jar=1987:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.3.6\bin" -Dfile.encoding=UTF-8 -classpath D:\software\java\jdk\jre\lib\charsets.jar;D:\software\java\jdk\jre\lib\deploy.jar;D:\software\java\jdk\jre\lib\ext\access-bridge-64.jar;D:\software\java\jdk\jre\lib\ext\cldrdata.jar;D:\software\java\jdk\jre\lib\ext\dnsns.jar;D:\software\java\jdk\jre\lib\ext\jaccess.jar;D:\software\java\jdk\jre\lib\ext\jfxrt.jar;D:\software\java\jdk\jre\lib\ext\localedata.jar;D:\software\java\jdk\jre\lib\ext\nashorn.jar;D:\software\java\jdk\jre\lib\ext\sunec.jar;D:\software\java\jdk\jre\lib\ext\sunjce_provider.jar;D:\software\java\jdk\jre\lib\ext\sunmscapi.jar;D:\software\java\jdk\jre\lib\ext\sunpkcs11.jar;D:\software\java\jdk\jre\lib\ext\zipfs.jar;D:\software\java\jdk\jre\lib\javaws.jar;D:\software\java\jdk\jre\lib\jce.jar;D:\software\java\jdk\jre\lib\jfr.jar;D:\software\java\jdk\jre\lib\jfxswt.jar;D:\software\java\jdk\jre\lib\jsse.jar;D:\software\java\jdk\jre\lib\management-agent.jar;D:\software\java\jdk\jre\lib\plugin.jar;D:\software\java\jdk\jre\lib\resources.jar;D:\software\java\jdk\jre\lib\rt.jar;E:\WorkSpace\JAVA\IDEA\concurrent\out\production\concurrent com.alpha.concurrent.test.CloseResource
reading...
shutdown all thread
close socket input
interrupted form blocked I/O
exit from reading.
Process finished with exit code 0
同步锁阻塞
针对synchronized锁阻塞的线程无法被中断,可以使用ReentrantLock给任务上锁,从而使其具备被中断的能力:
package com.alpha.concurrent.test;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class BlockedMutex {
private Lock lock = new ReentrantLock();
public BlockedMutex() {
lock.lock();
}
public void f() {
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
System.out.println("Interrupted from lock acquisition in f()");
}
}
}
class LockTask implements Runnable {
BlockedMutex blockedMutex = new BlockedMutex();
@Override
public void run() {
System.out.println("waiting for f() in BlockedMutex");
blockedMutex.f();
System.out.println("Broken out of blocked call");
}
}
public class Interrupting2 {
public static void main(String[] args) {
Thread t = new Thread(new LockTask());
t.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("interrupt");
t.interrupt();
}
}
输出结果如下:
D:\software\java\jdk\bin\java.exe "-javaagent:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.3.6\lib\idea_rt.jar=2049:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.3.6\bin" -Dfile.encoding=UTF-8 -classpath D:\software\java\jdk\jre\lib\charsets.jar;D:\software\java\jdk\jre\lib\deploy.jar;D:\software\java\jdk\jre\lib\ext\access-bridge-64.jar;D:\software\java\jdk\jre\lib\ext\cldrdata.jar;D:\software\java\jdk\jre\lib\ext\dnsns.jar;D:\software\java\jdk\jre\lib\ext\jaccess.jar;D:\software\java\jdk\jre\lib\ext\jfxrt.jar;D:\software\java\jdk\jre\lib\ext\localedata.jar;D:\software\java\jdk\jre\lib\ext\nashorn.jar;D:\software\java\jdk\jre\lib\ext\sunec.jar;D:\software\java\jdk\jre\lib\ext\sunjce_provider.jar;D:\software\java\jdk\jre\lib\ext\sunmscapi.jar;D:\software\java\jdk\jre\lib\ext\sunpkcs11.jar;D:\software\java\jdk\jre\lib\ext\zipfs.jar;D:\software\java\jdk\jre\lib\javaws.jar;D:\software\java\jdk\jre\lib\jce.jar;D:\software\java\jdk\jre\lib\jfr.jar;D:\software\java\jdk\jre\lib\jfxswt.jar;D:\software\java\jdk\jre\lib\jsse.jar;D:\software\java\jdk\jre\lib\management-agent.jar;D:\software\java\jdk\jre\lib\plugin.jar;D:\software\java\jdk\jre\lib\resources.jar;D:\software\java\jdk\jre\lib\rt.jar;E:\WorkSpace\JAVA\IDEA\concurrent\out\production\concurrent com.alpha.concurrent.test.Interrupting2
waiting for f() in BlockedMutex
interrupt
Interrupted from lock acquisition in f()
Broken out of blocked call
Process finished with exit code 0
检查中断
当你在线程上调用interrupt()时,只有当线程准备进入阻塞或者已经处于阻塞状态时,才会抛出InterruptedException异常,如果只依靠该异常,当线程不处于阻塞状态时调用interrupt()就不能离开run中的循环,因此需要在run()循环中使用interrupted()检查中断状态:
package com.alpha.concurrent.test;
import java.util.concurrent.TimeUnit;
class NeedsCleanup {
private final int id;
public NeedsCleanup(int id) {
this.id = id;
System.out.println("NeedsCleanup " + id);
}
public void cleanup() {
System.out.println("Cleaning up " + id);
}
}
class Block3 implements Runnable {
private volatile double d = 0.0;
@Override
public void run() {
try {
while (!Thread.interrupted()) {
// point1
NeedsCleanup n1 = new NeedsCleanup(1);
try {
System.out.println("Sleeping");
TimeUnit.SECONDS.sleep(1);
// point2
NeedsCleanup n2 = new NeedsCleanup(2);
try {
System.out.println("Calculating");
// time comsuming
for (int i = 1; i < 2500000; i++) {
d = d + (Math.PI + Math.E) / d;
}
System.out.println("finished Calculating");
} finally {
n2.cleanup();
}
} finally {
n1.cleanup();
}
}
System.out.println("exit while");
} catch (InterruptedException e) {
System.out.println("exit by interrupted");
}
}
}
public class InterruptingIdiom {
public static void main(String[] args) throws Exception {
Thread t = new Thread(new Block3());
t.start();
TimeUnit.SECONDS.sleep(1);
t.interrupt();
}
}
输出1:
D:\software\java\jdk\bin\java.exe "-javaagent:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.3.6\lib\idea_rt.jar=2300:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.3.6\bin" -Dfile.encoding=UTF-8 -classpath D:\software\java\jdk\jre\lib\charsets.jar;D:\software\java\jdk\jre\lib\deploy.jar;D:\software\java\jdk\jre\lib\ext\access-bridge-64.jar;D:\software\java\jdk\jre\lib\ext\cldrdata.jar;D:\software\java\jdk\jre\lib\ext\dnsns.jar;D:\software\java\jdk\jre\lib\ext\jaccess.jar;D:\software\java\jdk\jre\lib\ext\jfxrt.jar;D:\software\java\jdk\jre\lib\ext\localedata.jar;D:\software\java\jdk\jre\lib\ext\nashorn.jar;D:\software\java\jdk\jre\lib\ext\sunec.jar;D:\software\java\jdk\jre\lib\ext\sunjce_provider.jar;D:\software\java\jdk\jre\lib\ext\sunmscapi.jar;D:\software\java\jdk\jre\lib\ext\sunpkcs11.jar;D:\software\java\jdk\jre\lib\ext\zipfs.jar;D:\software\java\jdk\jre\lib\javaws.jar;D:\software\java\jdk\jre\lib\jce.jar;D:\software\java\jdk\jre\lib\jfr.jar;D:\software\java\jdk\jre\lib\jfxswt.jar;D:\software\java\jdk\jre\lib\jsse.jar;D:\software\java\jdk\jre\lib\management-agent.jar;D:\software\java\jdk\jre\lib\plugin.jar;D:\software\java\jdk\jre\lib\resources.jar;D:\software\java\jdk\jre\lib\rt.jar;E:\WorkSpace\JAVA\IDEA\concurrent\out\production\concurrent com.alpha.concurrent.test.InterruptingIdiom
NeedsCleanup 1
Sleeping
NeedsCleanup 2
Calculating
finished Calculating
Cleaning up 2
Cleaning up 1
exit while
Process finished with exit code 0
输出2:
D:\software\java\jdk\bin\java.exe "-javaagent:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.3.6\lib\idea_rt.jar=2311:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.3.6\bin" -Dfile.encoding=UTF-8 -classpath D:\software\java\jdk\jre\lib\charsets.jar;D:\software\java\jdk\jre\lib\deploy.jar;D:\software\java\jdk\jre\lib\ext\access-bridge-64.jar;D:\software\java\jdk\jre\lib\ext\cldrdata.jar;D:\software\java\jdk\jre\lib\ext\dnsns.jar;D:\software\java\jdk\jre\lib\ext\jaccess.jar;D:\software\java\jdk\jre\lib\ext\jfxrt.jar;D:\software\java\jdk\jre\lib\ext\localedata.jar;D:\software\java\jdk\jre\lib\ext\nashorn.jar;D:\software\java\jdk\jre\lib\ext\sunec.jar;D:\software\java\jdk\jre\lib\ext\sunjce_provider.jar;D:\software\java\jdk\jre\lib\ext\sunmscapi.jar;D:\software\java\jdk\jre\lib\ext\sunpkcs11.jar;D:\software\java\jdk\jre\lib\ext\zipfs.jar;D:\software\java\jdk\jre\lib\javaws.jar;D:\software\java\jdk\jre\lib\jce.jar;D:\software\java\jdk\jre\lib\jfr.jar;D:\software\java\jdk\jre\lib\jfxswt.jar;D:\software\java\jdk\jre\lib\jsse.jar;D:\software\java\jdk\jre\lib\management-agent.jar;D:\software\java\jdk\jre\lib\plugin.jar;D:\software\java\jdk\jre\lib\resources.jar;D:\software\java\jdk\jre\lib\rt.jar;E:\WorkSpace\JAVA\IDEA\concurrent\out\production\concurrent com.alpha.concurrent.test.InterruptingIdiom
NeedsCleanup 1
Sleeping
NeedsCleanup 2
Calculating
finished Calculating
Cleaning up 2
Cleaning up 1
NeedsCleanup 1
Sleeping
Cleaning up 1
exit by interrupted
Process finished with exit code 0