线程同步的输出的有关问题
线程同步的输出的问题,在线等
public class SyncTest {
public static void main(String[] args) {
final StringBuffer s1=new StringBuffer();
final StringBuffer s2=new StringBuffer();
new Thread(){
public void run(){
synchronized(s1){
s2.append("A");
synchronized(s2){
s2.append("B");
System.out.println(s1);
System.out.println(s2);
}
}
}
}.start();
new Thread(){
public void run(){
synchronized(s2){
s2.append("C");
synchronized(s1){
s1.append("D");
System.out.println(s2);
System.out.println(s1);
}
}
}
}.start();
}
}
Which two statements are true? (Choose Two)
A. The program prints “ABBCAD”
B. The program prints “CDDACB”
C. The program prints “ADCBADBC”
D. The output is a non-deterministic point because of a possible deadlock condition.
E. The output is dependent on the threading model of the system the program is running on.
答案是b d
请问为什么是选这二个呢,尽量详细点说明,多谢了
------解决思路----------------------
首先两个线程有两个资源s1和s2,第一个线程是先请求s1,再请求s2;第二个线程是先请求s2,再请求s1.由于你无法控制哪个线程先运行,哪个线程后运行,这是由cpu控制的。所以这个两个线程的运行会发生以下几种情况:1、死锁。当线程1获得资源s1后,线程2获得资源s2后,线程1尝试获得资源s2,线程2尝试获得资源s1,此时会发生死锁。2、线程1先运行结束,然后释放资源s2和s1,这时的打印顺序为:ABBCAD 。3、线程2先运行结束,然后释放相关资源s1和s2,这时的打印顺序为:CDDACB。
------解决思路----------------------
楼上说的对,但是那个假设线程1先运行的结果好像是ABABCD,线程2的话好像是CDDCAB
public class SyncTest {
public static void main(String[] args) {
final StringBuffer s1=new StringBuffer();
final StringBuffer s2=new StringBuffer();
new Thread(){
public void run(){
synchronized(s1){
s2.append("A");
synchronized(s2){
s2.append("B");
System.out.println(s1);
System.out.println(s2);
}
}
}
}.start();
new Thread(){
public void run(){
synchronized(s2){
s2.append("C");
synchronized(s1){
s1.append("D");
System.out.println(s2);
System.out.println(s1);
}
}
}
}.start();
}
}
Which two statements are true? (Choose Two)
A. The program prints “ABBCAD”
B. The program prints “CDDACB”
C. The program prints “ADCBADBC”
D. The output is a non-deterministic point because of a possible deadlock condition.
E. The output is dependent on the threading model of the system the program is running on.
答案是b d
请问为什么是选这二个呢,尽量详细点说明,多谢了
------解决思路----------------------
首先两个线程有两个资源s1和s2,第一个线程是先请求s1,再请求s2;第二个线程是先请求s2,再请求s1.由于你无法控制哪个线程先运行,哪个线程后运行,这是由cpu控制的。所以这个两个线程的运行会发生以下几种情况:1、死锁。当线程1获得资源s1后,线程2获得资源s2后,线程1尝试获得资源s2,线程2尝试获得资源s1,此时会发生死锁。2、线程1先运行结束,然后释放资源s2和s1,这时的打印顺序为:ABBCAD 。3、线程2先运行结束,然后释放相关资源s1和s2,这时的打印顺序为:CDDACB。
------解决思路----------------------
楼上说的对,但是那个假设线程1先运行的结果好像是ABABCD,线程2的话好像是CDDCAB