记录学习的点滴(Java多线程计数器)

    xiaoxiao2021-03-25  57

    1、 public class Counter1 {  private static AtomicInteger count = new AtomicInteger(0);    public synchronized static void addCounter(){   count.incrementAndGet();  }

     public static void main(String[] args) {   for (int i = 0;  i < 10000; i++) {    new Thread(new Runnable() {     @Override     public void run() {      addCounter();     }    }).start();       }      try {    Thread.sleep(1000);   } catch (InterruptedException e) {    e.printStackTrace();   }      System.out.println("计数器的值:" + count);  } } 2、 public class Counter2 {

     public static void main(String[] args) {   final ExecutorService pools = Executors.newFixedThreadPool(10);   final CountDownLatch begin = new CountDownLatch(1);   final CountDownLatch count = new CountDownLatch(10);   for (int i = 0; i < 10; i++) {    final int index = i;    Runnable runnable = new Runnable() {          @Override     public void run() {      try {       begin.await();       Thread.sleep((long)Math.random() * 1000);       System.out.println("运动员" + index + "到达终点。");      } catch (InterruptedException e) {       e.printStackTrace();      } finally {       count.countDown();      }     }    };    pools.execute(runnable);   }      try {    System.out.println("开始。");    begin.countDown();    count.await();    System.out.println("结束。");    pools.shutdown();   } catch (InterruptedException e) {    // TODO Auto-generated catch block    e.printStackTrace();   }  } }

    转载请注明原文地址: https://ju.6miu.com/read-40140.html

    最新回复(0)