实际上,有很多可能性,有些极不可能,但它们仍然是可能的,经过 100 万次处决后,这就是我发现的。
代码:
public class Stone implements Runnable {
static int id = 1;
static StringBuffer buffer = new StringBuffer();
public void run() {
try {
id = 1 - id;
if (id == 0) {
pick();
} else {
release();
}
} catch (Exception e) {
}
}
private static synchronized void pick() throws Exception {
buffer.append("P ");
buffer.append("Q ");
}
private synchronized void release() throws Exception {
buffer.append("R ");
buffer.append("S ");
}
public static void main(String[] args) {
int count = 1000000;
Map<String, Integer> results = new HashMap<String, Integer>();
System.out.println("Running " + count + " times...");
for (int i = 0; i< count; i++) {
buffer = new StringBuffer();
Stone stone = new Stone();
Thread t1 = new Thread(stone);
Thread t2 = new Thread(stone);
t1.start();
t2.start();
while (t1.isAlive() || t2.isAlive()) {
// wait
}
String result = buffer.toString();
Integer x = results.get(result);
if (x == null) x = 0;
results.put(result, x + 1);
if (i > 0 && i % 50000 == 0) System.out.println(i + "... " + results.keySet());
}
System.out.println("done, results were:");
for (String key : results.keySet()) {
System.out.println(" " + key + ": " + results.get(key));
}
}
}
结果:
Running 1000000 times...
50000... [R S P Q , P Q R S , P R S Q , R P Q S ]
100000... [R S P Q , P Q R S , P R S Q , R P Q S ]
150000... [R S P Q , P Q R S , P R S Q , R P Q S ]
200000... [R S P Q , P Q R S , P R S Q , R P Q S ]
250000... [R S P Q , P Q R S , P R S Q , R P Q S ]
300000... [R S P Q , P Q R S , P R S Q , R P Q S ]
350000... [R S P Q , P Q R S , P R S Q , P R Q S , R P Q S ]
400000... [R S P Q , P Q R S , P R S Q , P R Q S , R P Q S ]
450000... [R S P Q , P Q R S , P R S Q , P R Q S , R P Q S ]
500000... [R S P Q , P Q R S , P R S Q , P R Q S , R P Q S ]
550000... [R S P Q , P Q R S , P R S Q , P R Q S , R P Q S ]
600000... [R S P Q , P Q R S , P R S Q , P R Q S , R P Q S ]
650000... [R S P Q , P Q R S , P R S Q , P R Q S , R P Q S ]
700000... [R S P Q , P Q R S , P R S Q , P R Q S , R P Q S ]
750000... [R S P Q , P Q R S , P R S Q , P R Q S , R P Q S ]
800000... [R S P Q , P Q R S , P R S Q , P R Q S , R P Q S ]
850000... [R S P Q , P Q R S , P R S Q , P R Q S , R P Q S ]
900000... [R S P Q , P Q R S , P R S Q , P R Q S , R P Q S ]
950000... [P Q P Q , R S P Q , P Q R S , P R S Q , P R Q S , R P Q S ]
done, results were:
P Q P Q : 1
R S P Q : 60499
P Q R S : 939460
P R S Q : 23
P R Q S : 2
R P Q S : 15
我认为我们已经证明这P Q P Q
确实是可能的,尽管概率极低,大约百万分之一......
[编辑:另一个运行,R S R S
也可以显示不同的结果:]
done, results were:
R S R S : 1
R P S Q : 2
P Q P Q : 1
R S P Q : 445102
P Q R S : 554877
P R S Q : 5
P R Q S : 2
R P Q S : 10