易学笔记--从0开始学JAVA(个人纯手工笔记共享 免费!免费!免费!)--比直接看书快N倍的速度掌握知识点--第21章 并发(二)

并发计数器与任务取消

第21章 并发/21.4 终结任务/21.4.1 装饰性花园--花园门口人数计时器

标签:作者:易学笔记  更多资料请联系微信或QQ:1776565180

 

 

  • 装饰性花园--花园门口人数计时器

 

  1. //: concurrency/OrnamentalGarden.java

    package concurrency;

    import java.util.concurrent.*;

    import java.util.*;

     

    import static net.mindview.util.Print.*;

     

    /**

     * 总的人数

     * @author Administrator

     *

     */

    class Count {

      private int count = 0;

      private Random rand = new Random(47);

      // Remove the synchronized keyword to see counting fail:

      public synchronized int increment() {

        int temp = count;

        if(rand.nextBoolean()) // Yield half the time

          Thread.yield();

        return (count = ++temp);

      }

      public synchronized int value() { return count; }

    }

     

    class Entrance implements Runnable {

      private static Count count = new Count();

     

      /**

       * 人数累加列表

       */

      private static List<Entrance> entrances =

        new ArrayList<Entrance>();

      /**

       * number:本线程人数

       */

      private int number = 0;

      // Doesn't need synchronization to read:

      private final int id;

      private static volatile boolean canceled = false;

      // Atomic operation on a volatile field:

      public static void cancel() { canceled = true; }

      public Entrance(int id) {

        this.id = id;

        // Keep this task in a list. Also prevents

        // garbage collection of dead tasks:

        entrances.add(this);

      }

      public void run() {

        while(!canceled) {

          synchronized(this) {

            ++number;

          }

          print(this + " Total: " + count.increment());

          try {

            TimeUnit.MILLISECONDS.sleep(100);

          } catch(InterruptedException e) {

            print("sleep interrupted");

          }

        }

        print("Stopping " + this);

    //    try {

    //    TimeUnit.SECONDS.sleep(1);

    // } catch (InterruptedException e) {

    //    // TODO Auto-generated catch block

    //    e.printStackTrace();

    // }

      }

      public synchronized int getValue() { return number; }

      public String toString() {

        return "Entrance " + id + ": " + getValue();

      }

      public static int getTotalCount() {

        return count.value();

      }

      /**

       * 汇总各个线程的值

       * @return

       */

      public static int sumEntrances() {

        int sum = 0;

        for(Entrance entrance : entrances)

          sum += entrance.getValue();

        return sum;

      }

    }

     

    public class OrnamentalGarden {

      public static void main(String[] args) throws Exception {

        ExecutorService exec = Executors.newCachedThreadPool();

        for(int i = 0; i < 5; i++)

          exec.execute(new Entrance(i));

        // Run for a while, then stop and collect the data:

        TimeUnit.SECONDS.sleep(1);

        /**

         * 发出取消操作

         */

        Entrance.cancel();

        exec.shutdownNow();

        /**

         * 在一定时间内等待run函数结束

         */

        if(!exec.awaitTermination(250, TimeUnit.MILLISECONDS))

          print("Some tasks were not terminated!");

        print("Total: " + Entrance.getTotalCount());

        print("Sum of Entrances: " + Entrance.sumEntrances());

      }

    } /* Output: (Sample)

    Entrance 0: 1 Total: 1

    Entrance 2: 1 Total: 3

    Entrance 1: 1 Total: 2

    Entrance 4: 1 Total: 5

    Entrance 3: 1 Total: 4

    Entrance 2: 2 Total: 6

    Entrance 4: 2 Total: 7

    Entrance 0: 2 Total: 8

    ...

    Entrance 3: 29 Total: 143

    Entrance 0: 29 Total: 144

    Entrance 4: 29 Total: 145

    Entrance 2: 30 Total: 147

    Entrance 1: 30 Total: 146

    Entrance 0: 30 Total: 149

    Entrance 3: 30 Total: 148

    Entrance 4: 30 Total: 150

    Stopping Entrance 2: 30

    Stopping Entrance 1: 30

    Stopping Entrance 0: 30

    Stopping Entrance 3: 30

    Stopping Entrance 4: 30

    Total: 150

    Sum of Entrances: 150

    *///:~

     


 

》》》》》未完:易学笔记--从0开始学JAVA(个人纯手工笔记共享 免费!免费!免费!)--比直接看书快N倍的速度掌握知识点--总共19章》》》》》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

易学笔记(qq:1776565180)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值