fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. public class Main {
  6. static class Thread1 extends Thread {
  7. Object lock;
  8. int counter = 10;
  9.  
  10. @Override public void run() {
  11. try {
  12. synchronized(lock) {
  13. while (true) {
  14. System.out.println("Hello from Thread1!");
  15. lock.wait();
  16. counter -= 1;
  17. if (counter == 0) {
  18. return;
  19. }
  20. lock.notify();
  21. }
  22. }
  23. } catch (Exception ex) {
  24. throw new RuntimeException(ex);
  25. }
  26. }
  27. }
  28.  
  29. static class Thread2 extends Thread {
  30. Object lock;
  31.  
  32. @Override public void run() {
  33. try {
  34. synchronized(lock) {
  35. lock.notify();
  36. while (true) {
  37. System.out.println("Hello from Thread2!");
  38. lock.wait();
  39. lock.notify();
  40. }
  41. }
  42. } catch (Exception ex) {
  43. throw new RuntimeException(ex);
  44. }
  45. }
  46. }
  47. public static void main (String[] args) throws Exception {
  48. Object sharedLock = new Object();
  49. Thread1 thread1 = new Thread1();
  50. Thread2 thread2 = new Thread2();
  51. thread1.lock = sharedLock;
  52. thread2.lock = sharedLock;
  53. thread1.start();
  54. Thread.sleep(123);
  55. thread2.start();
  56. thread1.join(1234);
  57. thread2.interrupt();
  58. thread2.join();
  59. }
  60. }
Success #stdin #stdout #stderr 0.04s 2315264KB
stdin
Standard input is empty
stdout
Hello from Thread1!
Hello from Thread2!
Hello from Thread1!
Hello from Thread2!
Hello from Thread1!
Hello from Thread2!
Hello from Thread1!
Hello from Thread2!
Hello from Thread1!
Hello from Thread2!
Hello from Thread1!
Hello from Thread2!
Hello from Thread1!
Hello from Thread2!
Hello from Thread1!
Hello from Thread2!
Hello from Thread1!
Hello from Thread2!
Hello from Thread1!
Hello from Thread2!
stderr
Exception in thread "Thread-1" java.lang.RuntimeException: java.lang.InterruptedException
	at Main$Thread2.run(Main.java:43)
Caused by: java.lang.InterruptedException
	at java.lang.Object.wait(Native Method)
	at java.lang.Object.wait(Object.java:502)
	at Main$Thread2.run(Main.java:38)