死鎖

一、死鎖類java

package com.ljb.app.deadlock;
/**
 * 死鎖(同步代碼塊同步對象)
 * @author LJB
 * @version 2015年3月10日
 */
public class Deadlock {
 String s1 = "我是s1";
 String s2 = "我是s2";
 
 int n = 1;
 
 public void write () {
  synchronized (s1) {
   try {
    Thread.sleep(500);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   synchronized (s2) {
    s1 = "我是s1,我被第" + n + "次修改";
    s2 = "我是s2,我被第" + n + "次修改";
   }
  }
  
  n++;
 }
 
 public void read () {
  synchronized (s2) {
   try {
    Thread.sleep(500);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   synchronized (s1) {
    System.out.println(s1 + "," + s2);
   }
  }
 }
}

二、死鎖線程app

 package com.ljb.app.deadlock;
/**
 * 死鎖線程
 * @author LJB
 * @version 2015年3月10日
 */
public class DeadlockRunnable implements Runnable{
 
 private Deadlock dlock;
 
 public DeadlockRunnable (Deadlock dlock) {
  this.dlock = dlock;
 }
 public void run() {
  for (int i = 0 ; i < 5 ; i++) {
   dlock.read();
   dlock.write();
  }
  
 }
}

三、測試類測試

package com.ljb.app.deadlock;
/**
 * 測試類
 * @author LJB
 * @version 2015年3月10日
 */
public class TestDeadlock {
 /**
  * @param args
  */
 public static void main(String[] args) {
  Deadlock dlock = new Deadlock();
  
  DeadlockRunnable drunnable = new DeadlockRunnable(dlock);
  
  Thread t1 = new Thread(drunnable);
  Thread t2 = new Thread(drunnable);
  
  t1.start();
  t2.start();
 }
}

運行結果:this

我是s1,我是s2spa

相關文章
相關標籤/搜索