1.自然结束(能自然结束尽量自然结束)
2.调用线程的stop()方法
public class StopThread {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(()->{
while(true){
System.out.println("go on");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
Thread.sleep(5000);
/**
* 不管线程处于什么状态,直接结束线程,容易产生数据不一致的问题,不建议使用。
* 比如说线程里有好几把锁,这几把锁解决的是数据一致性的问题。
* 比如说a=1,b=2。这两个操作要都成功数据才会一致。但是a=1了之后,b还没来得及赋值,线程就被stop了。
* 不建议使用!!!
*/
t.stop();
}
}
3.使用线程suspend()和resume()方法
suspend() --暂停一个线程
resume() --启动一个线程
public class SuspendAndResume {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(()->{
while(true){
System.out.println("go on");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
Thread.sleep(3000);
/**
* 暂停线程 和stop一样,都会容易产生数据不一致的问题,区别就是stop是停止线程,suspend是暂停线程
* 不建议使用!!!
*/
t.suspend();
Thread.sleep(3000);
t.resume();//启动线程
}
}
4.使用volatile变量来判断线程是否结束
public class VolatileThread {
public static volatile boolean flag = true;
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
int i = 0;
while(flag){
i++;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("thread t end i="+i);
});
t.start();
Thread.sleep(3000);
flag = false;
/**
* 结论:volatile修饰的变量在多线程中具有可见性。
* 这种方式有一定的局限性,因为他不可以控制线程结束的执行。比如说有一个循环,让他循环10次的时候停止线程。这种volatile就做不到
* 而且如果线程中有类似sleep、wait等阻塞方法的时候,线程会被阻塞,走不到循环判断变量是否为true哪一步,是不会停止的
* 但是在特定的场景中volatile是有作用的
*/
}
}
5.使用static interrupted()方法判断线程是否结束
public class InterruptThread {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
while(!Thread.interrupted()){
System.out.println("线程执行中!!");
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
break;
}
}
System.out.println("thread t end!");
});
t.start();
Thread.sleep(3000);
/**
* 结论:这种方法和volatile修饰变量来判断线程是否停止的方法类似
* 但是会比volatile修饰变量来判断线程是否停止的方法优雅一点
* 因为如果线程中有sleep、wait等这些阻塞方法的时候,可以catch异常来进行处理
* 但是还是不可以精确的控制线程什么时候结束!!!
*/
t.interrupt();
}
}