读书人

关于多线程的有关问题

发布时间: 2012-02-10 21:27:42 作者: rapoo

关于多线程的问题
麻烦大家看一下下边的程序片断的输出为什么是

in thread 2 maple
in thread 1 maple

我在两个线程里都用sychronized把a锁掉了阿,为什么会出现并发访问的问题,难道sleep()会释放对象锁??


public class ThreadTest {

static String a = " ";

public static void main(String[] args) {

Thread thread1 = new Thread() {

public void run() {

synchronized (a) {

a = "lincoln ";

try {

Thread.sleep(500);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println( "in thread 1 " + a);
}

}

};

Thread thread2 = new Thread() {

public void run() {

synchronized (a) {

a = "maple ";

try {

Thread.sleep(100);



} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println( "in thread 2 " + a);

}

}

};

thread1.start();

thread2.start();

}

}


[解决办法]
和你的一摸一样啊

public class ThreadTest {

static String a = " ";


public static void main(String[] args) {

Thread thread1 = new Thread() {

public void run() {

synchronized ( " ") {

a = "lincoln ";

try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println( "in thread 1 " + a);

}
}
};

Thread thread2 = new Thread() {

public void run() {

synchronized ( " ") {

a = "maple ";

try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println( "in thread 2 " + a);
}

}
};

thread1.start();

thread2.start();

}

}

读书人网 >J2SE开发

热点推荐