package Threads;
public class DielockThread extends Thread{
static Object o1=new Object();
static Object o2=new Object();
boolean flag;
public DielockThread(boolean flag){
this.flag=flag;
}
@Override
public void run() {
if(flag==true){
synchronized (o1){
System.out.println("if o1");
synchronized (o2){
System.out.println("if o2");
}
}
}
else{
synchronized (o2){
System.out.println("else o2");
synchronized (o1){
System.out.println("else o1");
}
}
}
}
}
package Threads;
public class Dielock2 {
public static void main(String[] args) {
DielockThread d1=new DielockThread(true);
DielockThread d2=new DielockThread(false);
d1.start();
d2.start();
}
}
package Threads;
public class DieLock {
public static void main(String[] args) {
StringBuffer s1=new StringBuffer();
StringBuffer s2=new StringBuffer();
new Thread(){
@Override
public void run() {
synchronized (s1){//s1有锁状态
s1.append("a");
s2.append("1");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (s2){//s2为有锁状态无法执行此代码块
s1.append("b");
s2.append("2");
System.out.println(s1);
System.out.println(s2);
}
}
}
}.start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (s2){//s2有锁状态
s1.append("c");
s2.append("3");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (s1){//s1为有锁状态无法执行此代码块
s1.append("d");
s2.append("4");
System.out.println(s1);
System.out.println(s2);
}
}
}
}).start();
}
}
第二个死锁状态无法输出