Thread
類的start()
方法用於開始執行線程。 此方法的結果是執行兩個併發運行的線程:當前線程(從調用start
方法返回)和另一個線程(執行其run
方法)。
start()
方法在內部調用Runnable
介面的run()
方法,以在單獨的線程中執行run()
方法中指定的代碼。
啟動線程執行以下任務:
- 它統計一個新線程
- 線程從初始狀態移動到可運行狀態。
- 當線程有機會執行時,它的目標
run()
方法將運行。
語法
public void start()
返回值
此方法沒有返回值。
異常
IllegalThreadStateException
- 如果多次調用start()
方法,則拋出此異常。
示例1: 通過擴展Thread
類
public class StartExp1 extends Thread
{
public void run()
{
System.out.println("Thread is running...");
}
public static void main(String args[])
{
StartExp1 t1=new StartExp1();
// this will call run() method
t1.start();
}
}
執行上面示例代碼,得到以下結果:
Thread is running...
示例2: 通過實現Runnable介面
public class StartExp2 implements Runnable
{
public void run()
{
System.out.println("Thread is running...");
}
public static void main(String args[])
{
StartExp2 m1=new StartExp2 ();
Thread t1 =new Thread(m1);
// this will call run() method
t1.start();
}
}
執行上面示例代碼,得到以下結果:
Thread is running...
示例3: 多次調用start()
方法時
public class StartExp3 extends Thread
{
public void run()
{
System.out.println("First thread running...");
}
public static void main(String args[])
{
StartExp3 t1=new StartExp3();
t1.start();
// It will through an exception because you are calling start() method more than one time
t1.start();
}
}
執行上面示例代碼,得到以下結果:
First thread running...
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)
at StartExp3.main(StartExp3.java:12)
上一篇:
Java Runtime類
下一篇:無