package com.test;
public class DeadLock {
String s1="我是S1";
String s2="我是S2";
int n = 1;
public void write(){
synchronized (s1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (s2) {
s1 = "修改s1----"+n+"次";
System.out.println(s1);
}
}
n++;
}
public void read(){
synchronized (s2) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (s1) {
s2 = "修改s2---"+n+"次";
System.out.println(s2);
}
}
n++;
}
}
package com.test;
public class MyDeadLock implements Runnable{
private DeadLock dl;
public MyDeadLock(DeadLock dl){
this.dl = dl;
}
@Override
public void run() {
for (int i = 0; i <10; i++) {
dl.read();
dl.write();
}
}
}
package com.test;
public class TestDead {
public static void main(String[] args) {
DeadLock dd = new DeadLock();
MyDeadLock md = new MyDeadLock(dd);
new Thread(md).start();
new Thread(md).start();
}
}