上代码
package com.gunsmoke;
public class TheadTest implements Runnable
{
@Override
public void run()
{
System.out.println("run方法start");
for(int index = 0; index < 100000; index++)
{
System.out.println(Thread.currentThread().getName() + " ->" + index);
}
System.out.println("run方法end");
}
public static void main(String[] args) throws InterruptedException
{
Thread thread = new Thread(new TheadTest());
thread.start();
Thread.sleep(1);
thread.interrupt();
}
}
执行结果线程没有因为interrupt方法而停止,因为在run方法中没有判断线程是否终止的代码,修改run方法为
@Override
public void run()
{
System.out.println("run方法start");
for(int index = 0; index < 100000 && !Thread.currentThread().isInterrupted(); index++)
{
System.out.println(Thread.currentThread().getName() + " ->" + index);
}
System.out.println("run方法end");
}
代码中添加了判断!Thread.currentThread().isInterrupted(),这样线程就能正常终止了,线程停止是线程自己说了算,这个判断逻辑是线程写。