package club.interview.concurrent.learn; import java.util.concurrent.locks.LockSupport; /** * 中断 没有这个线程状态 * {@link Thread#interrupt()} 标记为中断 * {@link Thread#isInterrupted()} 不会清除标志位 * {@link Thread#interrupted()} 静态方法 会清除标志位 * thread.interrupt(); thread.isInterrupted() Thread.interrupted() * 阻塞 block 等锁 * * @author QuCheng on 2020/6/22. */ public class ThreadStatus { public static void main(String[] args) { Object lock = new Object(); new Thread(() -> { synchronized (lock) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); Thread thread = new Thread(() -> { try { Thread.sleep(100); LockSupport.park(); synchronized (lock) { System.out.println("get lock"); } } catch (InterruptedException e) { System.out.println("haha" + Thread.interrupted()); } System.out.println("thread is finished"); }); System.out.println("1 " + thread.getState()); thread.start(); System.out.println("2 " + thread.getState()); try { Thread.sleep(50); System.out.println("3 " + thread.getState()); Thread.sleep(60); System.out.println("4 " + thread.getState()); LockSupport.unpark(thread); Thread.sleep(1); System.out.println("5 " + thread.getState()); System.out.println("5.1 isInterrupted = " + thread.isInterrupted()); thread.interrupt(); System.out.println("5.2 isInterrupted = " + thread.isInterrupted()); System.out.println("5.3 " + thread.getState()); thread.join(); System.out.println("6 " + thread.getState()); } catch (InterruptedException e) { System.out.println("sleep is interrupted"); } } }
结果
1 NEW
2 RUNNABLE
3 TIMED_WAITING
4 WAITING
5 BLOCKED
5.1 isInterrupted = false
5.2 isInterrupted = true
5.3 BLOCKED
get lock
thread is finished
6 TERMINATED