Skip to content

Instantly share code, notes, and snippets.

@yuizho
Last active February 6, 2016 06:27
Show Gist options
  • Save yuizho/1d9f872c5da4a5861d1c to your computer and use it in GitHub Desktop.
Save yuizho/1d9f872c5da4a5861d1c to your computer and use it in GitHub Desktop.
Java thread practice
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class App {
private static final int COUNT = 10;
public static void main( String[] args ) throws InterruptedException {
// 10回カウントするCountDownLatchを生成
CountDownLatch countDownLatch = new CountDownLatch(COUNT);
// Threadを3つ生成するExecutorServiceを生成
ExecutorService exec = Executors.newFixedThreadPool(3);
for (int i = 0; i < COUNT; i++) {
exec.submit(new TestRunnable(countDownLatch));
}
// 各TestRunnableオブジェクトに渡したcountDownLatchオブジェクト
// のカウントダウンがすべて修了するまで待ち受け。
countDownLatch.await();
System.out.println("finished!");
}
}
import java.util.concurrent.CountDownLatch;
public class TestRunnable implements Runnable {
private final CountDownLatch countDownLatch;
TestRunnable(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
public void run() {
// 処理を実行してから受け取ったCountDownLatchをカウントアップ
System.out.println(Thread.currentThread().getId());
countDownLatch.countDown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment