/**
* 资源共享的示例
* 装饰性花园仿真程序
* 花园委员会希望知道每天通过多个大门进入公园的总人数
* 每个大门都有一个十字专转门或某种形式的计数器,
* 并且任何一个十字转门的计数值递增时,
* 就表示公园的总人数的共享计数值也会递增
*
* @author cxp
* @data 2016-08-29
* @modify
*
*/
class Count {
private int count =
0;
private Random rand =
new Random(
47);
public synchronized int increment() {
int temp = count;
if (rand.nextBoolean())
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>();
private int number =
0;
private final int id;
private static volatile boolean canceled =
false;
public static void cancel() {
canceled =
true;
}
public Entrance(
int id) {
this.id = id;
entrances.add(
this);
}
@Override
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);
}
public synchronized int getValue() {
return number;
}
@Override
public String
toString() {
return "Entrance " + id +
": " + getValue();
}
public static int getTotalCount() {
return count.value();
}
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));
TimeUnit.SECONDS.sleep(
3);
Entrance.cancel();
exec.shutdown();
if (!exec.awaitTermination(
250, TimeUnit.MILLISECONDS))
print(
"Some task were not terminated");
print(
"Total:" + Entrance.getTotalCount());
print(
"Sum of Entrances:" + Entrance.sumEntrances());
}
}
转载请注明原文地址: https://ju.6miu.com/read-1201434.html