public class Main
{
public static String v;
public static void main(String[] args)
{
for (int i = 0; i < 10; i++)
{
Thread t1 = new SubThread("t1");
Thread t2 = new SubThread("t2");
v = "main";
t1.start();
System.out.println(v);
t2.start();
}
}
}
public class SubThread extends Thread
{
private String m;
public SubThread(String m)
{
this.m = m;
}
public void run()
{
Main.v = m;
}
}以上代码的某一次输出
main
t2
main
t1
main
t2
t1
t2
t2
t1
经多次实验,为什么会输出t2,在每次System.out.println(v);之前,我只是进行v = "main";和t1.start();,并没有start t2这个线程,而start t2这个线程,必定是在System.out.println(v);之后,请各位帮忙看下。
改变v是在sub线程的run()里做的,
t1.start()
t2.start()
你又没有用join,wait,sleep
两个子线程到底什么时候调度,谁也说不准
出main,t1,t2都有可能
将Thread t1 = new SubThread("t1");
Thread t2 = new SubThread("t2");改为Thread t1 = new SubThread("t1 "+i);
Thread t2 = new SubThread("t2 "+i);
运行下就知道了,是上次的
我在每次循环结束后,加上Thread.sleep(1000); 这样确保本次循环开始时,上次t1和t2已经执行完,全部打出main了。