fork(4) download
  1.  
  2.  
  3.  
  4. public class Main {
  5. public static void main(String[] args) {
  6. // These are the two resources R1 and R2 Thread thr1 and thr2 try to get locks for
  7. final Object R1 = "Resource1";
  8. final Object R2 = "Resource2";
  9. // Here's the first thread. It tries to lock R1 then R2
  10. Thread thr1 = new Thread() {
  11. public void run() {
  12. // Lock resource 1
  13. synchronized(R1) {
  14. System.out.println("Thread 1: Acquired and Locked resource 1");
  15.  
  16. //Force deadlock by sleeping for sometime so that thread2 can come and
  17. //acquire lock for R2
  18. try { Thread.sleep(100); }
  19. catch (InterruptedException e) {}
  20. System.out.println("Thread 1: Trying to acquire lock on R2");
  21. // Now wait 'till we can get a lock on resource 2
  22. synchronized(R2) {
  23. System.out.println("Thread 1: Acquired and Locked resource 2");
  24. }
  25. }
  26. }
  27. };
  28.  
  29. // Here's the second thread. It tries to lock resource2 then resource1
  30. Thread thr2 = new Thread() {
  31. public void run() {
  32. // This thread locks resource 2 right away
  33. synchronized(R2) {
  34. System.out.println("Thread 2: Acquired and Locked resource 2");
  35.  
  36. // Then it pauses, for the same reason as the first thread does
  37. try { Thread.sleep(100); }
  38. catch (InterruptedException e) {}
  39.  
  40. System.out.println("Thread 2: Trying to acquire lock on R1");
  41.  
  42. synchronized(R1) {
  43. System.out.println("Thread 2: Acquired and Locked resource 1");
  44. }
  45. }
  46. }
  47. };
  48.  
  49. // Start the two threads. If all goes as planned, deadlock will occur,
  50. // and the program will never exit.
  51. thr1.start();
  52. thr2.start();
  53. }
  54. }
Time limit exceeded #stdin #stdout 5s 380864KB
stdin
Standard input is empty
stdout
Thread 1: Acquired and Locked resource 1
Thread 2: Acquired and Locked resource 2
Thread 1: Trying to acquire lock on R2
Thread 2: Trying to acquire lock on R1