学习心得
线程终止的3种方法:stop(),interrupt(),使用标志位。
总结
1.stop()方法会直接杀死线程不论执行到哪里,破坏了线程的安全性,已停止使用。
public class StopThread extends Thread{
public int i=0;
public int j=0;
@Override
public void run(){
i++;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
j++;
}
public static void main(String[] args) throws InterruptedException {
StopThread stopThread = new StopThread();
stopThread.start();
Thread.sleep(1000); //进入线程,执行i++
stopThread.stop(); //立即打断线程
//stopThread.interrupt(); //打断wait(),join(),sleep(),继续执行其他
while (stopThread.isAlive()){
}
System.out.println(stopThread.i+"***"+stopThread.j); //输出 1***0
}
}
2.interrupt()方法会打断当前等待或阻塞状态使线程继续执行,直至线程结束。
public class StopThread extends Thread{
public int i=0;
public int j=0;
@Override
public void run(){
i++;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
j++;
}
public static void main(String[] args) throws InterruptedException {
StopThread stopThread = new StopThread();
stopThread.start();
Thread.sleep(1000); //进入线程,执行i++
//stopThread.stop(); //立即打断线程
stopThread.interrupt(); //打断wait(),join(),sleep(),继续执行其他
while (stopThread.isAlive()){
}
System.out.println(stopThread.i+"***"+stopThread.j); //输出 1***1,并抛出异常。
}
}
3.增加标志位方法,标志位需使用voliate关键字修饰,保证多线程之间的可见性。
public class StopThread extends Thread{
public int i=0;
public int j=0;
public static voliate boolean falg = true; //volicate保证多线程可见性
@Override
public void run(){
while(flag){
i++;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
j++;
}
}
public static void main(String[] args) throws InterruptedException {
StopThread stopThread = new StopThread();
stopThread.start();
Thread.sleep(1000); //进入线程,执行i++
stopThread.falg = false;
while (stopThread.isAlive()){
}
System.out.println(stopThread.i+"***"+stopThread.j); //输出 1***1
}
}

3957

被折叠的 条评论
为什么被折叠?



