1、自然结束,线程能够顺利完成执行(能自然结束就自然结束)
2、废弃方法stop()、suspend()、resume(),容易造成线程不一致或者死锁的问题
@Test
public void function(){
Thread t = new Thread(() -> {
while (true){
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("t is running");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
try {
TimeUnit.SECONDS.sleep(6);
} catch (InterruptedException e) {
e.printStackTrace();
}
//stop()方法会释放掉当前线程持有的锁,从而造成数据不一致的问题
t.stop();
}
package com.yang.Threads;
import java.util.concurrent.TimeUnit;
public class TestMain {
public static void main(String[] args) {
Thread t2 = new Thread(()->{
while(true){
try {
TimeUnit.SECONDS.sleep(1);
System.out.println("t2 is running");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t2.start();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.suspend();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.resume();
}
}
3、使用volatile定义的标识位(可取)
package com.yang.Threads;
import java.util.concurrent.TimeUnit;
public class TestMain1 {
private static volatile boolean running = true;
public static void main(String[] args) {
Thread t = new Thread(()->{
long i = 0L;
while (running){
//如果里边包含wait()等方法,循环内部会阻塞住,无法结束
i++;
}
System.out.println("最终结果result为:"+i);
});
t.start();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
running = false;
}
}
}
4、使用interrupt()给线程设置标识位(可取,相对优雅)
package com.yang.Threads;
import java.util.concurrent.TimeUnit;
public class TestMain2 {
public static void main(String[] args) {
Thread t = new Thread(()->{
long i = 0L;
//可以使用!Thread.interrupted()或者!Thread.currentThread().isInterrupted()判断标识位
while (!Thread.currentThread().isInterrupted()){
i++;
}
System.out.println("最终结果result为:"+i);
});
t.start();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//给t设置标识位
t.interrupt();
}
}
}



