park & unpark
调用LockSupport.park()会阻塞当前的线程,LockSupport.unPark()会唤醒当前线程
public class ParkAndUnPark { public static void main(String[] args) { MyThread1 thread1 = new MyThread1(Thread.currentThread()); thread1.start(); System.out.println("before park"); //阻塞当前线程,当前线程 setBlocker(Blocker:拦截者,阻塞者,相当于是一个标志) LockSupport.park("parkAndUnParkDemo"); System.out.println("after park"); } } class MyThread1 extends Thread{ private Object object; public MyThread1(Object o){ this.object = o; } @Override public void run(){ System.out.println("before unpark"); try { Thread.sleep(1000); }catch (InterruptedException e){ e.printStackTrace(); } System.out.println("Blocker info " + LockSupport.getBlocker((Thread) object)); LockSupport.unpark((Thread) object); try { Thread.sleep(500); }catch (InterruptedException e){ e.printStackTrace(); } System.out.println("Blocker info " + LockSupport.getBlocker((Thread) object)); System.out.println("after unpark"); } }
LockSupport.park("parkAndUnParkDemo")源码
先设置当前线程的Blocker,再调用UNSAFE.park()阻塞当前线程,直到调用unpark()函数,当前线程会继续执行,并设置Blocker = null
public static void park(Object blocker) { Thread t = Thread.currentThread(); setBlocker(t, blocker); UNSAFE.park(false, 0L); setBlocker(t, null); }
此外LockSupport.park()不会释放锁,这里不会释放thread1这把锁,thread1这个线程一直无法拿到锁,无法调用unpark()函数,主线程会一直处于阻塞状态
public class ParkAndUnPark { public static void main(String[] args) { MyThread1 thread1 = new MyThread1(Thread.currentThread()); synchronized (thread1){ thread1.start(); System.out.println("before park"); //阻塞当前线程,当前线程 setBlocker(Blocker:拦截者,阻塞者,相当于是一个标志) LockSupport.park("parkAndUnParkDemo"); System.out.println("after park"); } } } class MyThread1 extends Thread{ private Object object; public MyThread1(Object o){ this.object = o; } @Override public synchronized void run(){ System.out.println("before unpark"); try { Thread.sleep(1000); }catch (InterruptedException e){ e.printStackTrace(); } System.out.println("Blocker info " + LockSupport.getBlocker((Thread) object)); LockSupport.unpark((Thread) object); try { Thread.sleep(500); }catch (InterruptedException e){ e.printStackTrace(); } System.out.println("Blocker info " + LockSupport.getBlocker((Thread) object)); System.out.println("after unpark"); } }
这里interrupt()(中断)和unpark()的效果一样
class MyThread extends Thread { private Object object; public MyThread(Object object) { this.object = object; } public void run() { System.out.println("before interrupt"); try { // 休眠3s Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } Thread thread = (Thread) object; // 中断线程 thread.interrupt(); System.out.println("after interrupt"); } } public class InterruptDemo { public static void main(String[] args) { MyThread myThread = new MyThread(Thread.currentThread()); myThread.start(); System.out.println("before park"); // 获取许可 LockSupport.park("ParkAndUnparkDemo"); System.out.println("after park"); } }

浙公网安备 33010602011771号