一道简单的面试题,问输出的结果是什么?
public class Tux extends Thread
{
static String sName="hello";
public static void main(String[] args) {
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 < 3; i++) {
sName=sName+" "+i;
}
}
}
输出结果是:hello,而不是预想的hello 0 1 2
这个程序结果运行是不稳定的(至少从理论上说是)
因为根本不知道线程什么时候执行完就打印,
所以写多线程程序时要避免出现这种情况