package com.yaspeed.threadnotice;
/**
* 测试线程死锁问题
* 问题分析:线程死锁的原因线程之间所需要的资源被对方占有不释放导致
* 例如:线程A有资源A1,线程B有资源B1,现在线程A占有A1的情况下,需要资源B1,
* 线程B占有B1的情况下需要A1,最终导致死锁的产生
* @author wd
*/
public class TestDeathLock {
static StringBuffer sb1 = new StringBuffer();
static StringBuffer sb2 = new StringBuffer();
static class Thread1 implements Runnable{
public void run(){
synchronized(sb1){
sb1.append("A");
synchronized(sb2){
sb2.append("B");
System.out.println(sb1.toString());
System.out.println(sb2.toString());
}
}
}
}
static class Thread2 implements Runnable{
public void run(){
synchronized(sb2){
sb2.append("C");
synchronized(sb1){
sb1.append("D");
System.out.println(sb1.toString());
System.out.println(sb2.toString());
}
}
}
}
public static void main(String[] args) {
Thread1 t1 = new TestDeathLock.Thread1();
Thread2 t2 = new TestDeathLock.Thread2();
Thread th1 = new Thread(t1);
Thread th2 = new Thread(t2);
th1.start();th2.start();
}
}