标签:
import java.util.concurrent.CountDownLatch; public class Test { public static void main(String[] args) { int num = 100000; test1(num); test2(num); } private static void test1(int max) { long t1 = System.currentTimeMillis(); int n = method1(max); long t2 = System.currentTimeMillis(); System.out.println("method1: value=" + n + ",time=" + (t2 - t1) / 1000.0); } private static int method1(int max) { int num = 0; for (int i = 1; i <= max; i++) { boolean flag = true; for (int j = 2; j < i - 1; j++) { if (i % j == 0) { flag = false; break; } } if (flag && i > num) num = i; } return num; } private static void test2(int max) { long t1 = System.currentTimeMillis(); int threadNumber = 10;//线程数 final CountDownLatch countDownLatch = new CountDownLatch(threadNumber); int step = max / threadNumber; for (int i = 0; i <= max; i += step) { if (i - step >= 0) { Calc calc = new Calc(i - step + 1, i, countDownLatch); Thread thread = new Thread(calc); thread.start(); } } try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } long t2 = System.currentTimeMillis(); System.out.println("method2: value=" + Calc.getVal() + ",time=" + (t2 - t1) / 1000.0); } } class Calc implements Runnable { private static Integer val = 0; private int min; private int max; private CountDownLatch cdl; public Calc(int min, int max, CountDownLatch cdl) { this.min = min; this.max = max; this.cdl = cdl; } public static int getVal() { return val; } public void run() { int num = 0; for (int i = min; i <= max; i++) { boolean flag = true; for (int j = 2; j < i - 1; j++) { if (i % j == 0) { flag = false; break; } } if (flag && i > num) num = i; } synchronized (val) { if (num > val) val = num; } cdl.countDown(); } }
public static void main(String[] args) { long t1 = System.currentTimeMillis(); Thread1.start(); Thread2.start(); Thread3.start(); Thread4.start(); Thread5.start(); long t2 = System.currentTimeMillis(); }
CountDownLatch这个类能够使一个线程等待其他线程完成各自的工作后再执行,构造器中的计数值(count)实际上就是闭锁需要等待的线程数量。这个值只能被设置一次,而且CountDownLatch没有提供任何机制去重新设置这个计数值。与CountDownLatch的第一次交互是主线程等待其他线程。主线程必须在启动其他线程后立即调用CountDownLatch.await()方法。这样主线程的操作就会在这个方法上阻塞,直到其他线程完成各自的任务。其他N 个线程必须引用闭锁对象,因为他们需要通知CountDownLatch对象,他们已经完成了各自的任务。这种通知机制是通过 CountDownLatch.countDown()方法来完成的;每调用一次这个方法,在构造函数中初始化的count值就减1。所以当N个线程都调 用了这个方法,count的值等于0,然后主线程就能通过await()方法,恢复执行自己的任务。
带你玩转java多线程系列 “道篇” 多线程的优势及利用util.concurrent包测试单核多核下多线程的效率
标签:
原文地址:http://www.cnblogs.com/winAlaugh/p/5478675.html