-
Java安全停止线程方法
- 1. 早期Java提供java.lang.Thread类型包含了一些列的方法 start(), stop(), stop(Throwable) and suspend(), destroy() and resume()。,Sun 公司的一篇文章 《Why are Thread.stop, Thread.suspend and Thread.resume Deprecated? 》
- 2.使用volatile变量来设置Thread的run的循环条件,保证变量同步性
-
- public class JavaTest extends Thread{
- private volatile boolean isRun = true;
- public static void main(String[] args) {
- JavaTest thread = new JavaTest();
- thread.start();
- thread.close();
- }
- @Override
- public void run() {
- while (isRun) {
-
- }
- }
- public void close() {
- this.isRun = false;
- }
- }
- 3.使用interrupt()来中止非运行状态的线程,如wait()和sleep()状态的线程,此时可利用interrupted来终止线程
- public class JavaTest extends Thread{
- private volatile boolean isRun = true;
- public static void main(String[] args) {
- JavaTest thread = new JavaTest();
- thread.start();
- thread.close();
- if (thread != null) {
- thread.interrupt();
- }
- }
- @Override
- public void run() {
- while (isRun) {
-
-
- try {
- wait();
- } catch (InterruptedException e) {
-
- }
- }
- }
- public void close() {
- this.isRun = false;
- }
- }
-
相关阅读:
大工程(bzoj 3611)
消耗战(bzoj 2286)
Computer(hdu 2196)
文件排版(codevs 1300)
洛谷 P2015 二叉苹果树
洛谷 P2014 选课
洛谷 P1352 没有上司的舞会
COGS 505. 城市
洛谷 P1306 斐波那契公约数
洛谷 P1962 斐波那契数列
-
原文地址:https://www.cnblogs.com/Free-Thinker/p/3465082.html
Copyright © 2020-2023
润新知