List<Thread> threads = new ArrayList<Thread>(); for (int i = 0; i < N; i++) { Thread t = newThread(r);
threads.add(t);
t.start();
}
// Wait till all threads have been started.
waitLatch.await();
// Hopefully enough time for all the threads to progress into wait. Thread.yield(); Thread.sleep(500);
// Wake up one.
lock(id);
rawNotify(id);
unlock(id);
wait2Latch.await();
// Wait a little bit more to see stragglers. This is flaky - spurious wakeups could // make the test fail. Thread.yield(); Thread.sleep(500); if (firstAwakened != null) {
firstAwakened.join();
}
// Wake up everyone else.
lock(id);
rawNotifyAll(id);
unlock(id);
// Wait for everyone to die. for (Thread t : threads) {
t.join();
}
// Check threaded output.
Iterator<String> it = output.iterator(); // 1) Start with N locks and Waits.
{ int locks = 0; int waits = 0; for (int i = 0; i < 2*N; i++) {
String s = it.next(); if (s.equals("Lock")) {
locks++;
} elseif (s.equals("Wait")) { if (locks <= waits) {
System.out.println(output); thrownew RuntimeException("Wait before Lock");
}
waits++;
} else {
System.out.println(output); thrownew RuntimeException("Unexpected operation: " + s);
}
}
}
// 5) N-1 threads wake up, run, and die.
{ int expectedUnlocks = 0; int ops = 2 * (N-1); for (int i = 0; i < ops; i++) {
String s = it.next(); if (s.equals("Awakened")) {
expectedUnlocks++;
} elseif (s.equals("Unlock")) {
expectedUnlocks--; if (expectedUnlocks < 0) {
System.out.println(output); thrownew RuntimeException("Unexpected unlock");
}
}
}
}
// 6) That should be it. if (it.hasNext()) {
System.out.println(output); thrownew RuntimeException("Unexpected trailing output, starting with " + it.next());
}
output.clear();
System.out.println("Done");
}
privatestaticvoid expect(String s, Iterator<String> it, List<String> output) {
String t = it.next(); if (!s.equals(t)) {
System.out.println(output); thrownew RuntimeException("Expected " + s + " but got " + t);
}
}
privatestaticvoid startWatchdog() {
Runnable r = new Runnable() {
@Override publicvoid run() { long start = System.currentTimeMillis(); // Give it a minute. long end = 60 * 1000 + start; for (;;) { long delta = end - System.currentTimeMillis(); if (delta <= 0) { break;
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.