Created
December 15, 2016 14:46
-
-
Save nkcoder/8cbdb56e146c96a867389df5b99f6802 to your computer and use it in GitHub Desktop.
CountDownLatch demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.nkcoder.module.javatest.concurrent; | |
import java.time.Duration; | |
import java.time.Instant; | |
import java.util.Random; | |
import java.util.concurrent.CountDownLatch; | |
/** | |
* created by daniel at 12/15/16 21:45 | |
*/ | |
public class CountDownLatchTest { | |
public static void main(String[] args) { | |
CountDownLatchTest latchTest = new CountDownLatchTest(); | |
int workers = 20; | |
Random r = new Random(Instant.now().getEpochSecond()); | |
final CountDownLatch startGate = new CountDownLatch(1); | |
final CountDownLatch endGate = new CountDownLatch(workers); | |
for (int i = 0; i < workers; i++) { | |
new Thread(() -> { | |
System.out.println("thread: " + Thread.currentThread().getName() + "..."); | |
try { | |
startGate.await(); | |
} catch (InterruptedException e) { | |
System.out.println("thread: " + Thread.currentThread().getName() + e); | |
Thread.currentThread().interrupt(); | |
} | |
latchTest.getFibonacci(r.nextInt(Integer.MAX_VALUE / 2)); | |
endGate.countDown(); | |
}).start(); | |
} | |
System.out.println("thread: " + Thread.currentThread().getName() + "start..."); | |
Instant begin = Instant.now(); | |
startGate.countDown(); | |
try { | |
endGate.await(); | |
} catch (InterruptedException e) { | |
System.out.println("thread: " + Thread.currentThread().getName() + e); | |
Thread.currentThread().interrupt(); | |
} | |
Instant end = Instant.now(); | |
System.out.println("thread: " + Thread.currentThread().getName() + "end..."); | |
Duration duration = Duration.between(begin, end); | |
System.out.println("duration(s): " + duration.getSeconds()); | |
} | |
private long getFibonacci(final long num) { | |
if (num == 1 || num == 2) { | |
return num; | |
} | |
long f1 = 1; | |
long f2 = 2; | |
for (long i = 3; i <= num; i++) { | |
long f = f1 + f2; | |
f1 = f2; | |
f2 = f; | |
} | |
System.out.println("num: " + num + ", fibonacci: " + f2); | |
return f2; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment