public class AltThread { public static void main(String[] args) { Q ob = new Q(); new thread1(ob); new thread2(ob); } } class thread1 extends Thread { Q ob; thread1(Q ob) { this.ob = ob; this.start(); } public void run() { while (true) { ob.one(); } } } class thread2 extends Thread { Q ob; thread2(Q ob) { this.ob = ob; this.start(); } public void run() { while (true) { ob.two(); try { this.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class Q{ static boolean toggle = false; public synchronized void one(){ while(!toggle){ try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } toggle = false; notify(); System.out.println("One"); } public synchronized void two(){ while(toggle){ try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } toggle = true; notify(); System.out.println("Two"); } }
Monday, October 1, 2012
Alternating execution of threads in java
Have you ever come across a need to execute two threads alternately? well to be truthful i never had the need, but this idea just came up and i decided to actually write the code that could make this happen.
In the code below i intentionally inserted a this.sleep(1000); to clearly show that the threads do in fact execute the way intended.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment