一个简单的死锁例子,希望对大家有用。、
写法一:
public class DeadLock{
static private Object o1="123";
static private Object o2="234";
public static void main(String[] args){
Thread t1 = new Thread1(o1,o2);
Thread t2 = new Thread2(o1,o2);
t1.start();
t2.start();
}
}
class Thread1 extends Thread{
Object o1;
Object o2;
public Thread1(Object o1,Object o2){
this.o1=o1;
this.o2=o2;
}
public void run(){
synchronized(o1){
System.out.println("线程一1");
try{
sleep(2000);
}catch(Exception e){
System.out.println("出错1");
}
synchronized(o2){
System.out.println("线程一2");
}
}
}
}
class Thread2 extends Thread{
Object o1;
Object o2;
public Thread2(Object o1,Object o2){
this.o1=o1;
this.o2=o2;
}
public void run(){
synchronized(o2){
System.out.println("线程二1");
try{
sleep(2000);
}catch(Exception e){
System.out.println("出错2");
}
synchronized(o1){
System.out.println("线程二2");
}
}
}
}
写法二:
public class Deadlock {
public static void main(String args[]) {
final Object o1 = "asd";
final Object o2 = "qwe";
Thread t1 = new Thread() {
public void run() {
synchronized (o1) {
System.out.println("Thread 1: locked o1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("error");
}
synchronized (o2) {
System.out.println("Thread1: locked o2");
}
}
}
};
Thread t2 = new Thread() {
public void run() {
synchronized (o2) {
System.out.println("Thread2: locked o2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("error");
}
synchronized (o1) {
System.out.println("Thread2: locked o1");
}
}
}
};
t1.start();
t2.start();
}
}
818

被折叠的 条评论
为什么被折叠?



