Thursday, June 21, 2018

How do you print Odd Even using Thread ?

Problem Statement: How will print Odd Even using Thread?
OR
How will you print t1 & t2 alternatively using thread?
  1. import java.util.concurrent.atomic.AtomicLong;
  2. class Even extends Thread {
  3. AtomicLong num;
  4. Object lock;
  5. Even(AtomicLong num, Object lock) { // constructor
  6. this.num = num;
  7. this.lock = lock;
  8. }
  9. public void run() {
  10. synchronized (lock) {
  11. while (true) { // infinite loop
  12. if (num.get() % 2 != 0) {
  13. try {
  14. lock.wait();
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. } else {
  19. System.out.println("even: " + num);
  20. try {
  21. Thread.sleep(1000);
  22. } catch (InterruptedException e) {
  23. e.printStackTrace();
  24. }
  25. num.incrementAndGet();
  26. lock.notifyAll();
  27. }
  28. }
  29. }
  30. }
  31. } // end of Even class

  32. class Odd extends Thread {
  33. AtomicLong num;
  34. Object lock;
  35. Odd(AtomicLong num, Object lock) { // constructor
  36. this.num = num;
  37. this.lock = lock;
  38. }
  39. public void run() {
  40. synchronized (lock) {
  41. while (true) { // infinite loop
  42. if (num.get() % 2 == 0) {
  43. try {
  44. lock.wait();
  45. } catch (InterruptedException e) {
  46. e.printStackTrace();
  47. }
  48. } else {
  49. System.out.println("odd: " + num);
  50. try {
  51. Thread.sleep(1000);
  52. } catch (InterruptedException e) {
  53. e.printStackTrace();
  54. }
  55. num.incrementAndGet();
  56. lock.notifyAll();
  57. }
  58. }
  59. }
  60. }
  61. } // end of Odd class

  62. public class EvenOddByThread {
  63. public static void main(String[] args) {
  64. AtomicLong num = new AtomicLong(1);
  65. Object lock = new Object();
  66. Odd odd = new Odd(num, lock);
  67. Even even = new Even(num, lock);
  68. even.start();
  69. odd.start();
  70. }
  71. } // end of EvenOddByThread class
Note: To print t1 & t2 alernatively, just replace the S.O.P. stmt with t1 & t2

Output: 

odd: 1
even: 2
odd: 3
even: 4
odd: 5
even: 6
odd: 7
even: 8
odd: 9
even: 10

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...