fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Counter {
  9. private int count = 0;
  10.  
  11. public synchronized void printOdd() {
  12. while(count%2==0){
  13. try{
  14. wait();
  15. Thread.currentThread().interrupt();
  16. }
  17. }
  18. System.out.println("ODD "+count);
  19. count++; // Thread-safe increment
  20.  
  21. notify();
  22. }
  23. public synchronized void printEven() {
  24. while(count%2==1){
  25. try{
  26. wait();
  27. Thread.currentThread().interrupt();
  28. }
  29. }
  30. System.out.println("EVEN "+count);
  31. count++; // Thread-safe increment
  32.  
  33. notify();
  34. }
  35. }
  36. class Ideone
  37. {
  38. public static void main (String[] args) throws java.lang.Exception
  39. {
  40. // your code goes here
  41. Counter c= new Counter();
  42. Thread t1 = new Thread(new Runnable(){
  43. @Override
  44. public void run(){
  45. for(int i=0;i<6;i++){
  46. c.printEven();
  47. }
  48. }
  49. }
  50. );
  51. Thread t2 = new Thread(new Runnable(){
  52. @Override
  53. public void run(){
  54. for(int i=0;i<5;i++){
  55. c.printOdd();
  56. }
  57. }
  58. }
  59. );
  60. t1.start();
  61. t2.start();
  62.  
  63. t1.join();
  64. t2.join();
  65. }
  66. }
Success #stdin #stdout 0.11s 57396KB
stdin
Standard input is empty
stdout
EVEN 0
ODD 1
EVEN 2
ODD 3
EVEN 4
ODD 5
EVEN 6
ODD 7
EVEN 8
ODD 9
EVEN 10