forked from destiny1020/algorithm_playground
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRobotCoin.java
More file actions
73 lines (54 loc) · 1.49 KB
/
RobotCoin.java
File metadata and controls
73 lines (54 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package misc;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class RobotCoin {
public static final int SIZE = 10000;
public static Boolean[] coins = new Boolean[SIZE];
static {
boolean standard = false;
for (int i = 0; i < SIZE; i++) {
coins[i] = standard;
standard = !standard;
}
}
public static void main(String[] args) throws InterruptedException {
int poolSize = 10;
ExecutorService es = Executors.newFixedThreadPool(poolSize);
for (int i = 0; i < poolSize; i++) {
es.execute(new Robot());
}
Thread.sleep(10000);
es.shutdownNow();
// check true/false distribution
int trueCoins = 0;
for (int i = 0; i < coins.length; i++) {
if (coins[i]) {
trueCoins++;
}
}
System.out.println("True Coins: " + trueCoins);
}
}
class Robot implements Runnable {
private Random rnd = new Random();
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
int coinNum = rnd.nextInt(RobotCoin.SIZE);
synchronized (RobotCoin.coins[coinNum]) {
if (RobotCoin.coins[coinNum] == false) {
boolean next = rnd.nextBoolean();
RobotCoin.coins[coinNum] = next;
System.out.println(Thread.currentThread().getName()
+ ": Coin " + coinNum + "false -> " + next);
} else {
RobotCoin.coins[coinNum] = false;
System.out.println(Thread.currentThread().getName()
+ ": Coin " + coinNum + "true -> false");
}
}
Thread.yield();
}
}
}