package com.thread.test;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class StaticIn
{
public static void main(String[] args)
throws InterruptedException
{
CountDownLatch begin = new CountDownLatch();
CountDownLatch end = new CountDownLatch();
ExecutorService exec = Executors.newFixedThreadPool();
StaticIn ss = new StaticIn();
for (int index = ; index < ; index++)
{
exec.submit(ss.new MyIn(begin, end));
}
System.out.println("Game Start");
// begin減一,開始遊戲
begin.countDown();
// 等待end變為0,即所有線程到達終點
end.await();
System.out.println("Game Over");
exec.shutdown();
System.out.println("now count is : " + count);
System.out.println("now sun is : " + sum);
}
static int count = ;
static AtomicInteger sum=new AtomicInteger();
class MyIn extends Thread
{
Random random = new Random();
// 開始的倒數鎖
CountDownLatch begin;
// 結束的倒數鎖
CountDownLatch end;
public MyIn(CountDownLatch begin_, CountDownLatch end_)
{
this.begin = begin_;
this.end = end_;
}
@Override
public void run()
{
try
{
begin.await();
Thread.sleep(random.nextInt());
count++;
sum.addAndGet();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
end.countDown();
}
}
}
}