public class Tux extends Thread
{
static String sName="hello";
public static void main(String[] args)throws Exception {
Tux t=new Tux();
t.piggy(sName); Thread.sleep(100);
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;
} }
}两个线程执行随机行,主线程先执行了,你让主线程休眠一会就可以了.
{
static String sName="hello";
public static void main(String[] args)throws Exception {
Tux t=new Tux();
t.piggy(sName); Thread.sleep(100);
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;
} }
}两个线程执行随机行,主线程先执行了,你让主线程休眠一会就可以了.
上面不是说得很清楚吗? 这是因为主线程提前执行完毕, sName还没来得被线程t改变就已经被打印出来了.
public class Tux extends Thread
{
static String sName="hello";
public static void main(String[] args) throws Exception{
Tux t=new Tux();
t.piggy(sName); t.join(); //<-------
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;
} }
}
cannot be changed
"static"关键字 定义的变量是不可以改变的.
你将static String sName="hello"; 改成String sName="hello"; 试试