退出标志
import lombok.SneakyThrows;
import java.text.SimpleDateFormat;
public class T {
static boolean flag = true;
@SneakyThrows
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
try {
while (flag) {
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + ":"
+ new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS").
format(System.currentTimeMillis()));
}
} catch (Exception e) {
e.printStackTrace();
}
}, "线程1");
thread1.start();
Thread.sleep(6000);
flag = false;
}
}
interrupt()
打断阻塞的线程(sleep/wait/joing),线程会抛出InterruptException异常
打断正常的线程,可以根据打断状态标记是否退出线程
阻塞线程
import lombok.SneakyThrows;
import java.text.SimpleDateFormat;
/*
线程1:2024-08-14 11:53:44 437
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at T.lambda$main$0(T.java:16)
at java.lang.Thread.run(Thread.java:748)
**/
public class T {
static boolean flag = true;
@SneakyThrows
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
try {
while (true) {
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + ":"
+ new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS").
format(System.currentTimeMillis()));
}
} catch (Exception e) {
e.printStackTrace();
}
}, "线程1");
thread1.start();
Thread.sleep(6000);
thread1.interrupt();
}
}
非阻塞线程
import lombok.SneakyThrows;
import java.text.SimpleDateFormat;
/*
正常退出
**/
public class T {
static boolean flag = true;
@SneakyThrows
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
try {
while (true) {
System.out.println(Thread.currentThread().getName() + ":"
+ new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS").
format(System.currentTimeMillis()));
Thread currentThread = Thread.currentThread();
boolean interrupted = currentThread.isInterrupted();
if (interrupted) {
System.out.println("打断状态" + interrupted);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}, "线程1");
thread1.start();
Thread.sleep(1000);
thread1.interrupt();
}
}
stop()
stop方法的作用是强制结束线程,就和kill -9一个效果,如果用stop来停止线程会直接结束线程,无视线程中对数据逻辑操作的完整性,这样是不安全。
import lombok.SneakyThrows;
import java.text.SimpleDateFormat;
public class T {
@SneakyThrows
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
try {
while (true) {
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + ":"
+ new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS").
format(System.currentTimeMillis()));
}
} catch (Exception e) {
e.printStackTrace();
}
}, "线程1");
thread1.start();
Thread.sleep(7000);
thread1.stop();
}
}
标签:java,Thread,stop,System,vs,线程,thread1,Interrupt,sleep
From: https://www.cnblogs.com/goodluckxiaotuanzi/p/18358641