1、死锁类
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);
}
}
}
}
2、死锁线程
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();
}
}
}
3、测试类
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();
}
}
运行结果:
我是s1,我是s2