105题里的两个题不会解!请高手指导!

sxxkxx 2004-04-08 03:41:28
49. class A implements Runnable{
public int i=1;
public void run(){
this.i=10;
}
}
public class Test{
public static void main(String args){
A a=new A();
11) new Thread(a).start();
int j=a.i;
13)
}
}
what is the value of j at line 13?
A. 1
B. 10
C. the value of j cannot be determined
D. An error at line 11 cause compilation to fail

50. public class SyncTest{
public static void main(String[] args){
final StringBuffer s1=new StirngBuffer();
final StringBuffer s2=new StirngBuffer();
new Thread(){
public void run(){
Synchronized(s1){
s1.append("A");
Synchronized(s2){
s2.append("B");
System.out.print(s1);
System.out.print(s2);
}
}
}
}.start();
new Thread(){
public void run(){
Synchronized(s2){
s2.append("C");
Synchronized(s1){
s1.append("D");
System.out.print(s2);
System.out.print(s1);
}
}
}
}.start();
}
}
what is the result?
A.the result depends on different system and different thread model
B.the result cannot be determined
...全文
39 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
qnake 2004-04-22
  • 打赏
  • 举报
回复
第2题的答案应该是:
1. The output is a non-deterministic point because of a possible deadlock condition
2. The output is dependent on the threading model of the system the program is
Taoists 2004-04-22
  • 打赏
  • 举报
回复
在打印j之前加一些等待,你就会发现j=10或1了
Taoists 2004-04-22
  • 打赏
  • 举报
回复
第一题是选C的,你们不能运行出来得的是j=1就说j=1,实际上他是不确定的。

你把代码改一下再运行就知道为什么了。
class A implements Runnable{
public int i=1;
public void run(){
this.i=10;
}
}
public class Test{
public static void main(String[] args){
A a=new A();
new Thread(a).start();
for(int i = 0;i<1000;i++)
System.out.println(i);
int j=a.i;
System.out.println("j="+j);
}
}
flyforlove 2004-04-14
  • 打赏
  • 举报
回复
"因为int j=a.i命令是在run()之前运行了!!!"

你怎么这么肯定?
zhaohaoMars 2004-04-14
  • 打赏
  • 举报
回复
楼上的线程学的是比较烂;呵呵
49选a,为了看的方便,我在13行那加了println(j);
首先:start()会调用线程的run()方法(它从参数a对象中得到run()方法)!!!
其次:这里为什么没有赋值为10,那是因为int j=a.i命令是在run()之前运行了!!!
也就是说println出1后,才被赋新值。
可以用join()测试:
上段代码写成:
C a=new C();
Thread zz = new Thread(a);
zz.start();
zz.join(); //new
int j=a.i;
System.out.println(j); //test

zz.join()是等run()函数执行玩了,在执行下面的命令。
去掉的话,输出1;留着的话,输出10;
over....
3456 2004-04-12
  • 打赏
  • 举报
回复
49选A,因为i不是类变量,所以在每一个实例中都有一份COPY,new Thread也是新建一个实例,一份COPY,所以int j = a.i;//j=1
50选B,感觉,呵呵~~我线程学的烂
qnake 2004-04-11
  • 打赏
  • 举报
回复
49是选A的,50也选A,进程的调度取决于系统来定的。
Sunonce 2004-04-09
  • 打赏
  • 举报
回复
同意49 a
charlie0895 2004-04-09
  • 打赏
  • 举报
回复
start()并不一定就run()了
flyforlove 2004-04-08
  • 打赏
  • 举报
回复
49,C //如果在给j赋值的时候,线程还没有执行,就等于1,如果已经执行了就等于10,所以不定。
beming 2004-04-08
  • 打赏
  • 举报
回复
49,a!
50,b?

50,549

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧