• Source
    1. /* codedaily.in - PrintSequence*/
    2.  
    3.  
    4. class PrintSequenceRunnable implements Runnable{
    5.  
    6. public int PRINT_NUMBERS_UPTO=10;
    7. static int number=1;
    8. int remainder;
    9. static Object lock=new Object();
    10.  
    11. PrintSequenceRunnable(int remainder)
    12. {
    13. this.remainder=remainder;
    14. }
    15.  
    16. @Override
    17. public void run() {
    18. while (number < PRINT_NUMBERS_UPTO-1) {
    19. synchronized (lock) {
    20. while (number % 3 != remainder) { // wait for numbers other than remainder
    21. try {
    22. lock.wait();
    23. } catch (InterruptedException e) {
    24. e.printStackTrace();
    25. }
    26. }
    27. System.out.println(Thread.currentThread().getName() + " " + number);
    28. number++;
    29. lock.notifyAll();
    30. }
    31. }
    32. }
    33. }
    34.  
    35.  
    36. class PrintThreadsSequentiallyMain {
    37.  
    38. public static void main(String[] args) {
    39.  
    40. PrintSequenceRunnable runnable1=new PrintSequenceRunnable(1);
    41. PrintSequenceRunnable runnable2=new PrintSequenceRunnable(2);
    42. PrintSequenceRunnable runnable3=new PrintSequenceRunnable(0);
    43.  
    44. Thread t1=new Thread(runnable1,"T1");
    45. Thread t2=new Thread(runnable2,"T2");
    46. Thread t3=new Thread(runnable3,"T3");
    47.  
    48. t1.start();
    49. t2.start();
    50. t3.start();
    51. }
    52. }
    53.