下面是SUN提供的说明,可以说是使用手册吧。这个是规定的,没有理由 /**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> method of this thread.
* <p>
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* <code>start</code> method) and the other thread (which executes its
* <code>run</code> method).
*
* @exception IllegalThreadStateException if the thread was already
* started.
* @see java.lang.Thread#run()
* @see java.lang.Thread#stop()
*/
* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> method of this thread.
* <p>
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* <code>start</code> method) and the other thread (which executes its
* <code>run</code> method).
*
* @exception IllegalThreadStateException if the thread was already
* started.
* @see java.lang.Thread#run()
* @see java.lang.Thread#stop()
*/
首先Thread只能start()一次,
在你的程序中start()了两此,第一次是有效的,第二次就不会起任何作用。线程start后,程序就出现了分支,这个分支就是你的线程,这样程序里就有两个线程,一个是主线程,一个是start后启动的线程,这两个线程并行运行,谁都可能先抢占到cpu,先运行,从你的运行结果来看,显然是主线程先运行,运行到一半的时候,子线程才开始运行,所以就会出现:
one.
thread
two.改成下面的程序后,就会出现这样的结果:
thread
one.
two.//MyThread.java
class MyThread extends Thread
{
public static void main(String [] args)
{
MyThread t=new MyThread();
t.start();
try{
Thread.sleep(10);
}catch(Exception e){}
System.out.println("one.");
t.start();
System.out.println("two.");
}
public void run()
{
System.out.println("thread");
}
}
public class MyThread extends Thread{
public static void main(String [] args){
MyThread t=new MyThread();
for(int i=0;i<100;i++){
t.start();
System.out.println("one.");
if(!t.isAlive()){
t=new MyThread();
t.start();
}
System.out.println("two.");
}
}
public void run()
{
System.out.println("thread");
}
}
借用宝地,请大家帮我看看问题出在哪里?