...
Code Block | ||
---|---|---|
| ||
public class Container implements Runnable { private final Vector<String> vector = new Vector<String>(); private final BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public Vector<String> getVector() { return vector; } public synchronized void run() { String string = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); do { System.out.println("Enter another string"); try { string = in.readLine(); } catch (IOException e) { // Forward to handler } vector.add(string); } while (!"END".equals(string)); } public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Container()); thread.start(); Thread.sleep(5000); thread.stop(); } } |
...
Code Block | ||
---|---|---|
| ||
public class Container implements Runnable { private final Vector<String> vector = new Vector<String>(); private volatilefinal boolean BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); private volatile boolean done = false; public Vector<String> getVector() { return vector; } public void shutdown() { done = true; } public synchronized void run() { String string = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); do { System.out.println("Enter another string"); try { string = in.readLine(); } catch (IOException e) { // Forward to handler } vector.add(string); } while (!done && !"END".equals(string)); } public static void main(String[] args) throws InterruptedException { ThreadContainer threadcontainer = new Thread(Container(); Thread thread = new ContainerThread()container); thread.start(); Thread.sleep(5000); ccontainer.shutdown(); } } |
Compliant Solution (Interruptible)
...
Code Block | ||
---|---|---|
| ||
public class Container implements Runnable { private final Vector<String> vector = new Vector<String>(); private final BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public Vector<String> getVector() { return vector; } public synchronized void run() { String string = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); do { System.out.println("Enter another string"); try { string = in.readLine(); } catch (IOException e) { // Forward to handler } vector.add(string); } while (!Thread.interrupted() && !"END".equals(string)); } public static void main(String[] args) throws InterruptedException { Container c = new Container(); Thread thread = new Thread(c); thread.start(); Thread.sleep(5000); thread.interrupt(); } } |
...