有一些辅助类真的不错:
1、CountDownLatch:等待其他几个(初始化值)任务执行完毕之后才能执行
public class Test { public static void main(String[] args) { final CountDownLatch latch = new CountDownLatch(2); new Thread(){ public void run() { try { Thread.sleep(1000); latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); new Thread(){ public void run() { try { Thread.sleep(1000); latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); try { latch.await(); System.out.println("主线程"); } catch (InterruptedException e) { e.printStackTrace(); } } }
2、CyclicBarrier:一组线程等待至某个事件发生再全部同时执行
final CyclicBarrier a = new CyclicBarrier(3, new Runnable() { @Override public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("好咯,其他人都执行吧~~~"); } }); new Thread(){ @Override public void run() { try { Thread.sleep(1000); a.await(); System.out.println("我是1"); } catch (Exception e) { e.printStackTrace(); } super.run(); } }.start(); new Thread(){ @Override public void run() { try { Thread.sleep(1000); a.await(); System.out.println("我是2"); } catch (Exception e) { e.printStackTrace(); } super.run(); } }.start(); new Thread(){ @Override public void run() { try { Thread.sleep(1000); a.await(); System.out.println("我是3"); } catch (Exception e) { e.printStackTrace(); } super.run(); } }.start();
3、Semaphore:主要通过acquire() 和release()这两个方法。类似于锁的概念,对某资源占用期间,他人不能使用。
final Semaphore s = new Semaphore(2); new Thread(){ public void run() { try { s.acquire(); System.out.println("开始使用资源1"); Thread.sleep(5000); System.out.println("放开资源1"); s.release(); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); new Thread(){ public void run() { try { s.acquire(); System.out.println("开始使用资源2"); Thread.sleep(5000); System.out.println("放开资源2"); s.release(); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); new Thread(){ public void run() { try { s.acquire(); System.out.println("开始使用资源3"); Thread.sleep(5000); System.out.println("放开资源3"); s.release(); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); new Thread(){ public void run() { try { s.acquire(); System.out.println("开始使用资源4"); Thread.sleep(5000); System.out.println("放开资源4"); s.release(); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start();