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 java.lang.Exception
  11. {
  12. final Object globalLock = new Object();
  13. Thread t1 = new Thread(new Runnable() {
  14. @Override
  15. public void run() {
  16. synchronized (globalLock) {
  17. System.out.println("thread1 grabbed the lock.");
  18. try {
  19. Thread.sleep(3000);
  20. } catch (InterruptedException e) {
  21. e.printStackTrace();
  22. }
  23. System.out.println("thread1 returned the lock.");
  24. }
  25. }
  26. });
  27. t1.start();
  28.  
  29. Thread.sleep(200);
  30.  
  31. Thread t2 = new Thread(new Runnable() {
  32. @Override
  33. public void run() {
  34. System.out.println("thread2 is waiting for the lock...");
  35. synchronized (globalLock) {
  36. System.out.println("thread2 got the lock");
  37. }
  38. }
  39. });
  40. t2.start();
  41. t1.join();
  42. t2.join();
  43. }
  44. }
Success #stdin #stdout 0.1s 320960KB
stdin
Standard input is empty
stdout
thread1 grabbed the lock.
thread2 is waiting for the lock...
thread1 returned the lock.
thread2 got the lock