Home java code which is 100% leading to Deadlock

code which is 100% leading to Deadlock

Author

Date

Category

I need to write the most simple code which in 100% start-up cases will lead to mutual blocking, but all the examples that I consider give only some probability. Is it possible to write this, if so, how would it look like in the simplest version?


Answer 1, Authority 100%

Public Class Testthread {
  Public Static Object Lock1 = New Object ();
  Public Static Object Lock2 = NEW OBJECT ();
  Public Static Void Main (String Args []) {
   Threaddemo1 T1 = new threaddemo1 ();
   Threaddemo2 t2 = new threaddemo2 ();
   T1.start ();
   T2.start ();
  }
  Private Static Class ThreadDemo1 EXTENDS THREAD {
   Public void Run () {
     Synchronized (Lock1) {
      System.out.PrintLN ("Thread 1: Holding Lock 1 ...");
      try {thread.sleep (10); }
      Catch (InterruptedException E) {}
      System.Out.printLN ("Thread 1: Waiting for Lock 2 ...");
      Synchronized (Lock2) {
        System.out.PrintLN ("Thread 1: Holding Lock 1 & amp; 2 ...");
      }
     }
   }
  }
  Private Static Class ThreadDemo2 EXTENDS THREAD {
   Public void Run () {
     Synchronized (Lock2) {
      System.out.PrintLN ("Thread 2: Holding Lock 2 ...");
      try {thread.sleep (10); }
      Catch (InterruptedException E) {}
      System.out.PrintLN ("Thread 2: Waiting for Lock 1 ...");
      Synchronized (Lock1) {
        System.out.PrintLN ("Thread 2: Holding Lock 1 & amp; 2 ...");
      }
     }
   }
  }
}

Source


Answer 2, Authority 90%

The easiest thing is probably running in one Synchronized method waiting for yourself in another stream.

Public Synchronized Static Void Deadlock () {
  Try {
    Thread T = New Thread (Test :: Deadlock);
    t.start ();
    t.join ();
  } Catch (Exception EX) {}
}

Check: http://ideone.com/ytbiky


An even shortest lock code:

new semapore (0) .acquire ();

But there is no multithreading in it, so this, depending on your presentation, may or may not be Deadlock.

Check: http://ideone.com/k1izqy

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions