A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 心弦上的景致 中级黑马   /  2013-1-30 10:31  /  1000 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1.     /*
  2.     CountDownLatch 闭锁:可以延迟线程的进度,直到锁到达终止状态。闭锁的作用相当于一扇门,在锁到达终止状态之前这扇门一直是关闭的。

  3. 当锁到达终止状态时,允许所有线程通过。CountDownLatch 有一个初始值,通过调用 countDown 可以减少该值,一直到 0 时到达终止状态。

  4.   FutureTask 用于执行一个可返回结果的长任务,任务在单独的线程中执行,其他线程可以用 get 方法取任务结果,如果任务尚未完成,

  5. 线程在 get 上阻塞。

  6.   Semaphore 用于控制同时访问某资源,或同时执行某操作的线程数目。信号量有一个初始值即可以分配的信号量总数目。线程任务开始前

  7. 先调用 acquire 取得信号量,任务结束后调用 release 释放信号量。在 acquire 是如果没有可用信号量,线程将阻塞在 acquire 上,直到

  8. 其他线程释放一个信号量。

  9.   CyclicBarrier 栅栏用于多个线程多次迭代时进行同步,在一轮任务中,任何线程完成任务后都在 barrier 上等待,直到所有其他线程也

  10. 完成任务,然后一起释放,同时进入下一轮迭代。
  11.    */

  12.   CountDownLatch 的例子:

  13.   import java.util.concurrent.CountDownLatch;

  14.   import java.util.concurrent.atomic.AtomicInteger;

  15.   public class DemoOfLatch {

  16.   // 利用闭锁 CountDownLatch 控制主线程和子线程的同步

  17.   public static void main(String[] args) {

  18.   int numberOfThread = 5;

  19.     //控制子线程开始

  20.   final CountDownLatch startLatch = new CountDownLatch(1);
  21.    
  22.     // 子线程计数               

  23.   final CountDownLatch stopLatch = new CountDownLatch(numberOfThread);   
  24.   
  25.     // 用于分配子线程唯一标识

  26.   final AtomicInteger count = new AtomicInteger(0);                     

  27.   System.out.println("Main thread start…");

  28.   for ( int i=0; i<numberOfThread; i++ ) {

  29.   Thread thread = new Thread( new Runnable() {

  30.   @Override

  31.   public void run() {

  32.   int tid = count.getAndIncrement();

  33.   try {

  34.   // 等代主线程打开启动信号

  35.   startLatch.await();

  36.   System.out.printf("Thread %d started…%n", tid);

  37.   int duration = (int)(Math.random() * 5000);

  38.   Thread.sleep(duration);

  39.   } catch (InterruptedException e) {

  40.   e.printStackTrace();

  41.   Thread.currentThread()。interrupt();

  42.   } finally {

  43.   System.out.printf("Thread %d stoped…%n", tid);

  44.   // 线程终止前减少线程计数

  45.   stopLatch.countDown();

  46.   }

  47.   }

  48.   });

  49.   thread.start();

  50.   }

  51.   // 在放行子线程之前做点什么别的事情

  52.   System.out.println("Main thread do preparation work for child threads…");

  53.   try {

  54.   Thread.sleep(2000);

  55.   } catch (InterruptedException e) {

  56.   e.printStackTrace();

  57.   }

  58.   // 打开闭锁放行所有子线程

  59.   System.out.println("Main thread let child threads go…");

  60.   startLatch.countDown();

  61.   try {

  62.   // 等待子线程计数降为 0 即所有子线程执行完毕

  63.   System.out.println("Main thread wait for all child threads…");

  64.   stopLatch.await();

  65.   } catch (InterruptedException e) {

  66.   e.printStackTrace();

  67.   }

  68.   System.out.println("Main thread exit…");

  69.   }

  70.   }

  71.    FutureTask 的例子:

  72.   import java.util.concurrent.Callable;

  73.   import java.util.concurrent.ExecutionException;

  74.   import java.util.concurrent.FutureTask;

  75.   public class DemoOfFutureTask {

  76.   public static void main(String[] args) {

  77.   // 创建一个 Future Task 用于并发执行长任务

  78.   final FutureTask<Movie> future = new FutureTask<Movie>( new Callable<Movie>() {

  79.   @Override

  80.   public Movie call() throws Exception {

  81.   System.out.println("Future task started…");

  82.   Thread.sleep(5000);

  83.   System.out.println("Future task finished…");

  84.   return new Movie("2012","Unknown");

  85.   }

  86.   }
  87.       );

  88.   // 在子线程中启动任务

  89.   Thread thread = new Thread(future);

  90.   thread.start();

  91.   // 主线程干点别的事情

  92.   System.out.println("Now let's do sth eles…");

  93.   try {

  94.   Thread.sleep(1000);

  95.   } catch (InterruptedException e1) {

  96.   e1.printStackTrace();

  97.   }

  98.   // 主线程开始取结果

  99.   System.out.println("Now wait for result of future task…");

  100.   try {

  101.   Movie res = future.get();

  102.   System.out.printf("Result from task is name=%s, actor=%s", res.name, res.actor);

  103.   } catch (InterruptedException e) {

  104.   e.printStackTrace();

  105.   } catch (ExecutionException e) {

  106.   e.printStackTrace();

  107.   }

  108.   }

  109.   public static class Movie {

  110.   final public String name;

  111.   final public String actor;

  112.   public Movie(String name, String actor) {

  113.   this.name = name;

  114.   this.actor = actor;

  115.   }

  116.   }

  117.   }

  118.   Semaphore 的例子:

  119.   import java.util.concurrent.Semaphore;

  120.   import java.util.concurrent.atomic.AtomicInteger;

  121.   public class DemoOfSemaphore {

  122.   public static void main(String[] args) {

  123.   final int numOfThread = 5;

  124.     // 分配唯一线程标识

  125.   final AtomicInteger count = new AtomicInteger(0);   

  126.     // 控制并发线程数目   

  127.   final Semaphore semaphore = new Semaphore(numOfThread);

  128.   for (int i = 0; i < 10; i++) {

  129.   Thread thread = new Thread(new Runnable() {

  130.   @Override

  131.   public void run() {

  132.   int tid = count.getAndIncrement();

  133.   try {
  134.    
  135.     // 等待直到取得信号量

  136.   System.out.printf("Thread %d wait on semaphore…%n", tid);

  137.   semaphore.acquire();

  138.   // 取得信号量之后做点事情

  139.   System.out.printf("Thread %d get semaphore…%n", tid);

  140.   int duration = (int)(Math.random() * 5000);

  141.   Thread.sleep(duration);

  142.   } catch (InterruptedException e) {

  143.   e.printStackTrace();

  144.   } finally {

  145.   // 做完后释放信号量

  146.   System.out.printf("Thread %d release semaphore…%n", tid);

  147.   semaphore.release();

  148.   }

  149.   }

  150.   });

  151.   thread.start();

  152.   }

  153.   }

  154.   }

  155.   CyclicBarrier 的例子:

  156.   import java.util.concurrent.BrokenBarrierException;

  157.   import java.util.concurrent.CyclicBarrier;

  158.   public class DemoOfBarrier {

  159.   public static void main(String[] args) {

  160.   final int numOfThread = 2;

  161.   final int numOfIteration = 2;

  162.   // 创建一个用于线程同步的 Barrier 对象

  163.   final CyclicBarrier barrier = new CyclicBarrier(numOfThread,

  164.   new Runnable() {

  165.   // 当所有线程到达 Barrier 后会执行这个任务

  166.   // 任务在第一个 到达 Barrier 的线程中执行

  167.   @Override

  168.   public void run() {

  169.   long tid = Thread.currentThread()。getId();

  170.   // 当所有线程完成一轮迭代之后做点清除/准备/提交工作

  171.   System.out.printf("[%d] - All threads arrived barrier…%n", tid);

  172.   try {

  173.   Thread.sleep(2000);

  174.   } catch (InterruptedException e) {

  175.   e.printStackTrace();

  176.   }

  177.   System.out.printf("[%d] - Clear work done…%n", tid);

  178.   }

  179.   });

  180.   // 创建并启动多个线程,他们在 Barrier 上同步

  181.   for (int i = 0; i < numOfThread; i++) {

  182.   Thread thread = new Thread(new Runnable() {

  183.   @Override

  184.   public void run() {

  185.   long tid = Thread.currentThread()。getId();

  186.   for ( int k=0; k<numOfIteration; k++ ) {

  187.   try {

  188.   // 线程进行一轮迭代

  189.   System.out.printf("Thread %d start its work…%n", tid);

  190.   long duration = (int)(Math.random()*5000);

  191.   Thread.sleep(duration);

  192.   // 做完迭代后等待其他线程完成迭代

  193.   System.out.printf("Thread %d wait on barrier…%n", tid);

  194.   int num = barrier.await();

  195.   // 显示完成的顺序

  196.   System.out.printf("Thread %d pass barrier with order=%d…%n", tid, num);

  197.   } catch (InterruptedException e) {

  198.   e.printStackTrace();

  199.   Thread.currentThread()。interrupt();

  200.   } catch (BrokenBarrierException e) {

  201.   e.printStackTrace();

  202.   }

  203.   }

  204.   }

  205.   });

  206.   thread.start();

  207.   }

  208.   }

  209.   }

复制代码

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马