Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. public class EvenOddPrinter {
  2. private volatile boolean odd = false;
  3. private int count = 1;
  4. private int MAX = 20;
  5.  
  6. public void printOdd() {
  7. synchronized (this) {
  8. while (!odd) {
  9. try {
  10. wait();
  11. } catch (InterruptedException ie) {
  12. ie.printStackTrace();
  13. }
  14. System.out.println("Odd Thread :" + count);
  15. count++;
  16. if (count == MAX) return;
  17. odd = false;
  18. notify();
  19. }
  20. }
  21. }
  22.  
  23. public void printEven() {
  24. synchronized (this) {
  25. while (odd) {
  26. try {
  27. wait();
  28. } catch (InterruptedException ie) {
  29. ie.printStackTrace();
  30. }
  31. System.out.println("Even Thread :" + count);
  32. count++;
  33. if (count == MAX) return;
  34. odd = true;
  35. notify();
  36. }
  37. }
  38. }
  39. }
  40.  
  41. public class PrintThread implements Runnable {
  42. private EvenOddPrinter printer;
  43. private String evenOddString;
  44.  
  45. public PrintThread(EvenOddPrinter printer, String evenOddString) {
  46. this.printer = printer;
  47. this.evenOddString = evenOddString;
  48. }
  49.  
  50. @Override
  51. public void run() {
  52. if (evenOddString.equalsIgnoreCase("odd")) printer.printOdd();
  53. else printer.printEven();
  54. }
  55. }
  56.  
  57. public class TesPrintEvenOdd {
  58. public static void main(String[] args) {
  59. EvenOddPrinter printer = new EvenOddPrinter();
  60. Thread th1 = new Thread(new PrintThread(printer, "Odd"));
  61. Thread th2 = new Thread(new PrintThread(printer, "Even"));
  62. th1.start();
  63. th2.start();
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement