package com;
/**
* java死锁例子
思路:生成二把锁,
1)线程1,加了一把锁a_lock的前提下又去寻找另外一把锁b_lock。
2) 线程1,加了一把锁b_lock的前提下又去寻找另外一把锁a_lock。
*
*/
public class ThreadDeadLock {
public static void main(String[] args) {
final Object o1= new Object();
final Object o2= new Object();
Thread t1 = new Thread("t1"){
@Override
public void run() {
synchronized ( o1 ) {
work();
synchronized( o2 ){
work();
}
}
}
};
t1.start();
Thread t2 = new Thread("t2"){
@Override
public void run() {
synchronized ( o2 ) {
work();
synchronized( o1 ){
work();
}
}
}
};
t2.start();
}
public static void work(){
try {
Thread.sleep( 2000 );
System.out.println( Thread.currentThread().getName() + "--> run");
} catch (InterruptedException e) {
}
}
}
/**
* java死锁例子
思路:生成二把锁,
1)线程1,加了一把锁a_lock的前提下又去寻找另外一把锁b_lock。
2) 线程1,加了一把锁b_lock的前提下又去寻找另外一把锁a_lock。
*
*/
public class ThreadDeadLock {
public static void main(String[] args) {
final Object o1= new Object();
final Object o2= new Object();
Thread t1 = new Thread("t1"){
@Override
public void run() {
synchronized ( o1 ) {
work();
synchronized( o2 ){
work();
}
}
}
};
t1.start();
Thread t2 = new Thread("t2"){
@Override
public void run() {
synchronized ( o2 ) {
work();
synchronized( o1 ){
work();
}
}
}
};
t2.start();
}
public static void work(){
try {
Thread.sleep( 2000 );
System.out.println( Thread.currentThread().getName() + "--> run");
} catch (InterruptedException e) {
}
}
}