当线程a需要线程b的资源,而b需要a线程的资源才能进行,便发生了死锁。具体实现如下:

/*
 * @(#)DeadlockRisk.java 1.0 06/08/07
 *
 * a simple sample for deadlock.
 * jiazhen 2006.08.07
 */
 import java.io.*;
 import java.lang.*;
 public class DeadlockRisk{
  private static class Resource{
   public int value;   
  }
  private resourceA =new Resource();
  private resourceB =new Resource();
  
  public int read(){
   synchronized(resourceA){
    synchronized(resourceB){
     return resourceB.value+resourceA.value; //可能死锁
    }
   }
  }
  
   public void write(int a,int b){
    synchronized(resourceB){
     synchronized(resourceA){  //可能死锁
      resourceA.value=a;
      resourceB.value=b;
     }
    }
   }
}