|
| 1 | +package com.xforg.concurrency; |
| 2 | +import java.util.ArrayList; |
| 3 | +import java.util.List; |
| 4 | +import java.util.Random; |
| 5 | +import java.util.concurrent.ExecutorService; |
| 6 | +import java.util.concurrent.Executors; |
| 7 | +import java.util.concurrent.TimeUnit; |
| 8 | + |
| 9 | +/** |
| 10 | + * Created by Administrator on 2016/4/27. |
| 11 | + */ |
| 12 | +class Count{ |
| 13 | + private int count = 0; |
| 14 | + private Random rand = new Random(47); |
| 15 | + public synchronized int increment(){ |
| 16 | + int temp = count; |
| 17 | + if(rand.nextBoolean()) |
| 18 | + Thread.yield(); |
| 19 | + return (count = ++temp); |
| 20 | + } |
| 21 | + public synchronized int value(){ |
| 22 | + return count; |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +class Entrance implements Runnable { |
| 27 | + private static Count count = new Count(); |
| 28 | + private static List<Entrance> entrances = new ArrayList<Entrance>(); |
| 29 | + private int number = 0; |
| 30 | + private final int id; |
| 31 | + private static volatile boolean canceled = false; |
| 32 | + |
| 33 | + public static void cancel() { |
| 34 | + canceled = true; |
| 35 | + } |
| 36 | + |
| 37 | + public Entrance(int id) { |
| 38 | + this.id = id; |
| 39 | + entrances.add(this); |
| 40 | + } |
| 41 | + |
| 42 | + public void run() { |
| 43 | + while (!canceled) { |
| 44 | + synchronized (this){ |
| 45 | + ++number; |
| 46 | + } |
| 47 | + System.out.println(this + "Total:" + count.increment()); |
| 48 | + try { |
| 49 | + TimeUnit.MILLISECONDS.sleep(100); |
| 50 | + } catch (InterruptedException e) { |
| 51 | + System.out.println("sleep interrupted"); |
| 52 | + } |
| 53 | + } |
| 54 | + System.out.println("Stoping this"); |
| 55 | + } |
| 56 | + |
| 57 | + public synchronized int getValue(){ |
| 58 | + return number; |
| 59 | + } |
| 60 | + public String toString(){ |
| 61 | + return "Entrance"+id+":"+getValue(); |
| 62 | + } |
| 63 | + public static int getTatalCount(){ |
| 64 | + return count.value(); |
| 65 | + } |
| 66 | + public static int sumEntrances(){ |
| 67 | + int sum = 0; |
| 68 | + for(Entrance entrance : entrances) |
| 69 | + sum +=entrance.getValue(); |
| 70 | + return sum; |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +public class OrnamentalGarden { |
| 75 | + public static void main(String[] args) throws Exception{ |
| 76 | + ExecutorService exec = Executors.newCachedThreadPool(); |
| 77 | + for(int i = 0; i < 10; i++){ |
| 78 | + exec.execute(new Entrance(i));/*开启了五个线程,类似于公园的五个大门*/ |
| 79 | + } |
| 80 | + TimeUnit.MILLISECONDS.sleep(3); |
| 81 | + Entrance.cancel(); |
| 82 | + exec.shutdown(); |
| 83 | + if(!exec.awaitTermination(250, TimeUnit.MICROSECONDS)) |
| 84 | + System.out.println("Some tasks were not terminated"); |
| 85 | + System.out.println("Total:"+Entrance.getTatalCount()); |
| 86 | + System.out.println("Sum of Entrance:"+ Entrance.sumEntrances()); |
| 87 | + } |
| 88 | +} |
0 commit comments