上QQ阅读APP看书,第一时间看更新
1.12.4 使用LockSupport类实现线程暂停与恢复
suspend()与resume()方法是过期作废的,若想实现同样的功能,也可以使用JDK并发包里提供的LockSupport类作为替代,效果是一样的。
创建测试项目park_unpark。
创建自定义线程类代码如下:
package mythread; import java.util.concurrent.locks.LockSupport; public class MyThread1 extends Thread { @Override public void run() { System.out.println("begin " + System.currentTimeMillis()); LockSupport.park(); System.out.println(" end " + System.currentTimeMillis()); } }
创建运行类代码如下:
package test; import java.util.concurrent.locks.LockSupport; import mythread.MyThread1; public class Test1 { public static void main(String[] args) throws InterruptedException { MyThread1 mythread = new MyThread1(); mythread.start(); Thread.sleep(4000); LockSupport.unpark(mythread); } }
运行结果如下:
begin 1616026920837 end 1616026924836
park()方法的作用是将线程暂停,unpark()方法的作用是恢复线程的运行。
如果先执行unpark()再执行park()方法,则park()方法不会呈暂停的效果。
创建自定义线程类代码如下:
package mythread; import java.util.concurrent.locks.LockSupport; public class MyThread2 extends Thread { @Override public void run() { try { System.out.println("begin " + System.currentTimeMillis()); Thread.sleep(5000); LockSupport.park(); System.out.println(" end " + System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } }
运行类代码如下:
package test; import java.util.concurrent.locks.LockSupport; import mythread.MyThread2; public class Test2 { public static void main(String[] args) throws InterruptedException { MyThread2 mythread = new MyThread2(); mythread.start(); Thread.sleep(2000); LockSupport.unpark(mythread); } }
运行结果如下:
begin 1616027833016 end 1616027838017