source: trunk/src/org/expeditee/core/BlockingRunnable.java@ 1097

Last change on this file since 1097 was 1097, checked in by davidb, 6 years ago

Newly structured files from Corey's work on logic/graphics separation

File size: 1.2 KB
Line 
1package org.expeditee.core;
2
3/**
4 * A Runnable which can be asked to block the calling thread until
5 * execution of the given code has completed. Runnable's run() method
6 * is used as part of the implementation so user code should be specified
7 * by overriding the execute() method instead.
8 *
9 * @author cts16
10 */
11public abstract class BlockingRunnable implements Runnable {
12
13 /** Whether the code has finished executing or not. */
14 private boolean _done;
15 /** Synchronisation object to prevent race conditions. */
16 private Object _lock;
17
18 public BlockingRunnable()
19 {
20 _done = false;
21 _lock = new Object();
22 }
23
24 /** Should be overridden to specify user behaviour. */
25 public abstract void execute();
26
27 @Override
28 public final void run()
29 {
30 execute();
31
32 // Mark as finished and wake any blocked threads
33 synchronized (_lock) {
34 _done = true;
35 _lock.notifyAll();
36 }
37 }
38
39 /** Can be called to block the calling thread until the execute() method returns. */
40 public final void blockUntilDone()
41 {
42 synchronized (_lock) {
43 while (!_done) {
44 try {
45 _lock.wait();
46 } catch (InterruptedException e) {
47 // Do nothing, just try waiting again
48 }
49 }
50 }
51 }
52}
Note: See TracBrowser for help on using the repository browser.