上海到舟山自驾走s2:求解java的考题

来源:百度文库 编辑:高校问答 时间:2024/04/29 09:34:52
What will happen when you attempt to compile and run the following code?

public class Tux extends Thread{ static String sName = "vandeleur"; public static void main(String argv[]){ Tux t = new Tux(); t.piggy(sName); System.out.println(sName); } public void piggy(String sName){ sName = sName + " wiggy"; start(); } public void run(){ for(int i=0;i < 4; i++){ sName = sName + " " + i; } }}

1) Compile time error
2) Compilation and output of "vandeleur wiggy"
3) Compilation and output of "vandeleur wiggy 0 1 2 3"
4) Compilation and output of either "vandeleur", "vandeleur 0", "vandeleur 0 1" "vandaleur 0 1 2" or "vandaleur 0 1 2 3"
Answer to Question 19

求解以及详细的为什么,谢谢

4)

首先 函数piggy 不会改变 静态变量 sName的值,因为它的参数名是sName,所以优先选择的是这个传入的参数。

其次 start() 会调用run()它会改变静态变量的值,因为Tux是一个Thread,所以run 会在另外一个线程运行,和主线程同时运行。然后主线程call System.out.println 此时 run 运行结果不定。