高并发编程_Java线程基础 3.优雅关闭线程
由于Thread类提供的关闭线程的方法只有stop,并且stop方法现在已经被标识为过时方法,不提倡使用。但是在开发中,及时关闭那些不在活动的线程、释放线程所占用的资源又只管重要。所以我们就需要寻找一些方法去关闭线程,释放资源。
1.使用interrupt机制优雅关闭线程
public class ThreadInterrupt {
private static final Object MONITOR = new Object();
public static void main(String[] args) {
Thread t = new Thread() {
@Override
public void run() {
while (true) {
}
}
};
t.start();
Thread main = Thread.currentThread();
Thread t2 = new Thread() {
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
main.interrupt();
System.out.println("interrupt");
}
};
t2.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2.使用标志位优雅关闭线程
public class ThreadCloseGraceful {
private static class Worker extends Thread {
private volatile boolean start = true;
@Override
public void run() {
while (start) {
//
}
}
public void shutdown() {
this.start = false;
}
}
public static void main(String[] args) {
Worker worker = new Worker();
worker.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
worker.shutdown();
}
}
3.使用Thread类API小技巧关闭线程
public class ThreadService {
private Thread executeThread;
private boolean finished = false;
public static void main(String[] args) {
long start = System.currentTimeMillis();
execute(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
shutdown(10000);
long end = System.currentTimeMillis();
System.out.println(end - start);
}
public void execute(Runnable task) {
executeThread = new Thread() {
@Override
public void run() {
Thread runner = new Thread(task);
runner.setDaemon(true);
runner.start();
try {
runner.join();
finished = true;
} catch (InterruptedException e) {
//e.printStackTrace();
}
}
};
executeThread.start();
}
public void shutdown(long mills) {
long currentTime = System.currentTimeMillis();
while (!finished) {
if ((System.currentTimeMillis() - currentTime) >= mills) {
System.out.println("任务超时,需要结束他!");
executeThread.interrupt();
break;
}
try {
executeThread.sleep(1);
} catch (InterruptedException e) {
System.out.println("执行线程被打断!");
break;
}
}
finished = false;
}
}
此次线程相关介绍就到这里,如有描述不当地方,请指正。文中案例代码多是根据汪文军老师的视频编写的,在此感谢!