// A demo of the existence of deadlock
package thread.deadlock;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity 
{
   @Override
   public void onCreate(Bundle savedInstanceState)
   {
     super.onCreate(savedInstanceState);
     Mutex mutexX = new Mutex( "mutexX" );
     Mutex mutexY = new Mutex( "mutexY" );
     
     // Thread A tries to acquire mutexX, then mutexY
     Athread A = new Athread( mutexX, mutexY, "A");
     // Thread B tries to acquire mutexY, then mutexX
     Athread B = new Athread( mutexY, mutexX, "B");
     
     A.start();
     B.start();
   }
}

class Mutex
{
  public String mname;
  public Mutex( String name )
  {
    mname = name;
  }
}

class Athread extends Thread
{
   private Mutex first, second;
   private String tname;
   
   public Athread(Mutex f, Mutex s, String name ) {
      first = f;
      second = s;
      tname = name;
   }
   
   public void run() {
     synchronized (first) {
         // do something
	   try { 
         Thread.sleep( ((int)(Math.random()+1))*1000);
	   } catch (InterruptedException e) {}
       Log.v ("Thread Info", tname + " thread got " + first.mname);
       synchronized (second) {
         // do something
         Log.v("Thread Info", tname + " thread got " + second.mname );	 
       }
     }
   }
}
