一:stop终止线程
举例子:
public class ThreadStop {
public static int i;
public static int j;
public static void main(String[] args) throws InterruptedException {
ThreadStop stop = new ThreadStop();
stop.test();
}
public void test() throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
i++;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
j++;
}
});
thread.start();
Thread.sleep(1000);
//存在线程安全问题,破坏线程的原子性
thread.stop();
System.out.println("i= " + i + ", j= " + j);
}
}
上述例子中,最后输出的i和j一个是1一个是0,按照正常情况,两个值应该都是1才对,所以可以看到,调用了stop之后,出现了这种问题,也就是说stop存在线程安全问题,会破坏线程的原子性。
二:Interrupt
Interrupt不会真的中止线程,只是给线程加上了一个标识,即isInterrupted从false变成了true;要是线程处于waiting、time waiting状态,再调用Interrupt会清除线程的阻塞状态,使线程状态变为runnable,而且isInterrupted也会从true变回false。下面举例子说明:
public static void main(String[] args) throws InterruptedException {
ThreadInterrupt1 thread = new ThreadInterrupt1();
thread.test();
}
public void test() throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println(Thread.currentThread().isInterrupted());
System.out.println(Thread.currentThread().getState());
}
}
});
thread.start();
Thread.sleep(1000);
thread.interrupt();
}
代码运行结果如下:
可以看到线程刚开始运行的时候isInterrupted是false,运行一会之后,isInterrupted变成了true。
栗子2:
public void test2() throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
System.out.println("running......");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println(Thread.currentThread().isInterrupted());
System.out.println(Thread.currentThread().getState());
}
}
}
});
thread.start();
Thread.sleep(1000);
thread.interrupt();
}
上面代码,线程sleep后处于阻塞状态,这个时候去执行Interrupt,会报java.lang.InterruptedException: sleep interrupted异常,而且线程的状态也变成了runnable,isInterrupted也从true变回false,并且打印running语句会继续执行,说明线程并没有真的被中止。运行结果如下:
栗子3:
public void test3() throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
//中止线程的正确方式,加个判断
while (!Thread.currentThread().isInterrupted()) {
System.out.println("running......");
Thread.currentThread().interrupt();
}
}
});
thread.start();
Thread.sleep(1000);
thread.interrupt();
}
上面的例子,能够正确的把线程中止,输出结果如下:
可以看到,输出一次之后就中止了线程,线程没有再挂起。
OK,到此结束。
—— 我自是年少,韶华倾负。