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 Ideone
  9. {
  10. public static void main(String[] args) throws Exception {
  11. testThreadWait();
  12. System.out.println(Thread.currentThread().getName() + " exiting");
  13. }
  14.  
  15. private static void testThreadWait() throws Exception {
  16. Thread thread1 = new Thread(() -> {
  17. String currentThread = Thread.currentThread().getName();
  18. System.out.println(String.format("%s execution started", currentThread));
  19. long waitMillis = 20000L;
  20. try {
  21. System.out.println(String.format("%s going for timed wait of %d millis", currentThread, waitMillis));
  22. Thread.sleep(waitMillis);
  23. } catch (InterruptedException e) {
  24. System.out.println(String.format("%s timed wait over after %d millis", currentThread, waitMillis));
  25. }
  26. System.out.println(String.format("%s execution ending", currentThread));
  27. });
  28. thread1.setName("Thread-1");
  29.  
  30. Thread thread2 = new Thread(() -> {
  31. String currentThread = Thread.currentThread().getName();
  32. System.out.println(String.format("%s execution started", currentThread));
  33. try {
  34. System.out.println(currentThread + " about to wait for " + thread1.getName());
  35. thread1.join();
  36. } catch (InterruptedException e) {
  37. System.out.println(String.format("%s wait over for %s", currentThread, thread1.getName()));
  38. }
  39. System.out.println(String.format("%s execution ending", currentThread));
  40. });
  41. thread2.setName("Thread-2");
  42.  
  43. thread2.start();
  44. thread1.start();
  45.  
  46. Thread.sleep(1000);
  47.  
  48. thread1.interrupt();
  49. thread2.interrupt();
  50. }
  51. }
Success #stdin #stdout 0.12s 37360KB
stdin
Standard input is empty
stdout
Thread-2 execution started
Thread-1 execution started
Thread-1 going for timed wait of 20000 millis
Thread-2 about to wait for Thread-1
Thread-1 timed wait over after 20000 millis
Thread-1 execution ending
Thread-2 wait over for Thread-1
Thread-2 execution ending
main exiting