参考文章
需求
我想使用Thread的方式来开启一个线程,如何使用才是比较好的呢?
学习到的知识点
1、直接使用thread.stop()的方式来终止是不好的
2、我通过while(!isInterrupted())来进行是否终止线程,发现会出现无法终止的情况
3、使用volatile标识 不会让多线程同时改变参数
代码展示
public class PayListThread extends Thread{
private int sleepTime = 1000 * 5;//默认睡眠5秒
private volatile boolean isNeed = true;
@Override
public void run() {
int ready = 0;
while (isNeed){
try {
Thread.sleep(sleepTime);
//这里处理你的业务
} catch (InterruptedException e) {
e.printStackTrace();
break;//捕获到异常之后,执行break跳出循环
}
}
}
/**
* @date: 2019/7/22 0022
* @author: gaoxiaoxiong
* @description:销毁线程
**/
public void detory() {
if (isNeed){
isNeed = false;
this.interrupt();
try {
this.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
当需要销毁线程的时候,需要调用destory的方法
网友评论