JAVA死锁问题

来源:百度知道 编辑:UC知道 时间:2024/06/13 01:26:40
为什么thread1里少了
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
就能正常输出
没有才死锁??
public static void main(String[] args) {
final StringBuffer s1 = new StringBuffer();
final StringBuffer s2 = new StringBuffer();

Thread thread1 = new Thread() { //线程1
public void run() {
synchronized (s1) { //线程1:s1锁定
s2.append("D"); //s2="D"
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
//上面不要就正常输出why

synchronized (s2) { //线程1:s2锁定
s2.append("E"); //s2="DE"
System.out.println(s1); //无输出
System.out.println(s2); //输出DE

只是一种可能情况让你赶上了,也就是说你thread1休眠了50毫秒 这个时间里 thread2并没有锁上 所以thread1直接执行完了。
只能说你不够幸运,你把50换大点!