写一个死锁
总被问到怎样写一个死锁,尝试了一下,成功!
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer();
StringBuffer s2 = new StringBuffer();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (s1){
try {
s1.append(Thread.currentThread().getName()+"我进入了1");
Thread.sleep(1000);
System.out.println(s1);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (s2){
s2.append(Thread.currentThread().getName()+"我进入了2");
System.out.println(s2);
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (s2){
try {
s2.append(Thread.currentThread().getName()+"我进入了2");
Thread.sleep(1000);
System.out.println(s2);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (s1){
s1.append(Thread.currentThread().getName()+"我进入了1");
System.out.println(s1);
}
}
}
}).start();
}