Playing intermittently makes your life unnecessarily difficult. Besides the fact that your code needs to know the threads, the interrupt does not provide any contextual information about the cause of the interrupt.
If you have a condition that is shared by your code, possibly executed by different threads, just encapsulate this condition in an object and share this object:
public class Test { public static void main(String[] args) { Condition c=new Condition(); new Thread(new Setter(c)).start(); new Thread(new Getter(c, "getter 1")).start();
The great advantage of this encapsulation is that it is easy to expand. Suppose you want to allow a thread to wait for a condition, rather than poll it. Taking the code above is easy:
class WaitableCondition extends Condition { public synchronized boolean await() { try { while(!super.isSatisfied()) wait(); return true; } catch(InterruptedException ex){ return false; } } public synchronized void setSatisfied() { if(!isSatisfied()) { super.setSatisfied(); notifyAll(); } } } class Waiter implements Runnable { final WaitableCondition condition; final String name; Waiter(WaitableCondition c, String n) { condition=c; name=n; } public void run() { System.out.println(name+": waiting for condition"); boolean b=condition.await(); System.out.println(name+": "+(b? "condition satisfied": "interrupted")); } }
Without changing other classes, you can now expand your test case:
public class Test { public static void main(String[] args) { WaitableCondition c=new WaitableCondition(); new Thread(new Setter(c)).start(); new Thread(new Getter(c, "getter 1")).start();
source share