1. 错误的停止方式
- stop()(已经废弃)
原因是stop会在线程没有执行完的时候强行停止线程,清除监视器锁的信息,如果一个线程计算一项工作完成一半突然停止,有可能导致数据不一致,与我们的期望不一致,可能导致线程安全问题
package com.example.thread;
public class StopThread extends Thread {
private int i = 0, j = 0;
@Override
public void run() {
synchronized (this) {
++i;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
++j;
}
}
public void print() {
System.out.println("i=" + i + ",j=" + j);
}
public static void main(String[] args) throws InterruptedException {
StopThread thread = new StopThread();
thread.start();
Thread.sleep(1000);
thread.stop();
while (thread.isAlive()) {
}
thread.print();
}
}
- 我们可以利用 thread.interrupt(); 或者 flag标志位去停止线程
- 利用thread.interrupt();
package com.example.thread;
public class InterruptThread extends Thread {
private int i = 0, j = 0;
@Override
public void run() {
synchronized (this) {
++i;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
++j;
}
}
public void print() {
System.out.println("i=" + i + ",j=" + j);
}
public static void main(String[] args) throws InterruptedException {
InterruptThread thread = new InterruptThread();
thread.start();
Thread.sleep(1000);
thread.interrupt();
while (thread.isAlive()) {
}
thread.print();
}
}
- 利用标志位,如果我们业务中有while循环,我们可以声明一个volatile变量的编制为flag=false,然后当条件达到时,在主线程中设置flag=true,停止子线程的运行