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();
}
}
}
}