线程的状态:
1 NEW 初始状态,没有调用start方法 A thread that has not yet started is in this state.
* 2 RUNNABLE 运行状态 A thread executing in the Java virtual machine is in this state.
* 3 BLOCKED 阻塞 A thread that is blocked waiting for a monitor lock
* 等待阻塞 wait
* 同步阻塞 synchronized
* 其他阻塞 sleep / join
* 4 WAITING 等待 A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
* 5 TIMED_WAITING 时间等待 A thread that is waiting for another thread to perform an action for up to a specified waiting time is in tsis state.
* 6 TERMINATED 终止 A thread that has exited is in this state.
线程的启动和终止:
start native
stop – 过时, 相当于 kill
interrupt 优雅中断
通过指令的方式 votatile Boolean isStop = false
Thread.interrupted(); 对设置的中断标识的线程进行复位
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
while (true){
boolean in = Thread.currentThread().isInterrupted();
if(in){
System.out.println("before:"+in);
Thread.interrupted(); //设置复位
System.out.println("after:"+Thread.currentThread().isInterrupted());
}
}
});
thread.start();
TimeUnit.SECONDS.sleep(1);
thread.interrupt();
}
线程的安全性问题:
-
可见性问题
-
原子性问题
-
有序性问题: 编译器的优化 指令重排序 但原则是保证不影响最终的结果。
CPU的高速缓存