一个简单的死锁示例
package cn.com.io.threadDemo.ThreadSyn;
/**
* 通过两个属性值创建死锁
* 本程序通过两个线程各自锁定一个属性值,这样两个线程都无法结束,造成死锁
*/
public class ThreadSyn2 implements Runnable{
private static Object obj1=new Object();
private static Object obj2=new Object(); //obj1和obj2是线程共享的,嵌套会引起死锁!
/**
* @param args
*/
public static void main(String[] args) {
ThreadSyn2 ts1=new ThreadSyn2();
ThreadSyn2 ts2=new ThreadSyn2();
Thread t1=new Thread(ts1);//线程1
Thread t2=new Thread(ts2);//线程2
t1.setName("theOne");
t2.setName("theTwo");
t1.start();
t2.start();
}
public void run() {
String name=Thread.currentThread().getName();
if(name.equals("theOne"))
{
method1(name);
}
else
{
method2(name);
}
}
//线程1的方法锁定obj1,线程2就无法完成
private void method1(String name) {
System.out.println(name);
synchronized(obj1){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(obj2){
System.out.println(obj2);
}
}
}
//线程1的方法锁定obj2,线程1就无法完成
private void method2(String name) {
System.out.println(name);
synchronized(obj2){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(obj1){
System.out.println(obj1);
}
}
}
}