Many times we face scenario where we need to execute two sequential tasks to perform a operation, like Tagging / Stamping serial Coupons , Producing serial Tickets at different Vending Machines. Below code ( generating Odd and Even in sequence) can be used for such requirement.
PS: This is a basic implementation, the same can be done using other Threading concepts.
package multithreading; // print ODD and Even number alternatively public class SquenceGeneratorTasks { public static boolean oddPrinted = false; public static void main(String[] args) { Object lock =new Object(); Thread oddThread = new Thread(new Runnable() { @Override public void run() { int i = 1; while (i <= 20) { synchronized (lock) { if (!oddPrinted) { // make sure printing starting with Odd number and each Odd is followed with a Even number System.out.println(i); i = i + 2; oddPrinted = true; lock.notify(); try { lock.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } }); Thread evenThread = new Thread(new Runnable() { @Override public void run() { System.out.println(" Though you have delayed Odd thread but printing gonna start with Odd number only !!"); int i = 2; while (i <= 20) { synchronized (lock) { if (oddPrinted) { System.out.println(i); i = i + 2; oddPrinted = false; lock.notify(); try { lock.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } }); evenThread.start(); // even if We apply some delay to Odd thread printing will start with ODD number only and // Sequence of Odd-Even-Odd maintained try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } oddThread.start(); } } /* Though you have delayed Odd thread but printing gonna start with Odd number only !! 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 */
You can download the same code from : https://github.com/SkilledMinds/easyNuts/tree/master/code-25-09-2015