Java start()方法
线程类的
start()方法用于开始执行线程。该方法的结果是两个线程同时运行: 当前线程(从调用返回到start方法)和另一个线程(执行其run方法)。
start()方法在内部调用Runnable接口的run()方法,以在单独的线程中执行run()方法中指定的代码。
启动线程执行以下任务:
它统计了一个新线程
线程从"新状态"移动到"可运行"状态。
当线程有机会执行时,其目标run()方法将运行。
语法
返回值
It does not return any value.
异常
IllegalThreadStateException -如果多次调用start()方法,则抛出此异常。
示例1: 通过扩展线程类
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();
}
}
输出:
示例2: 通过实现可运行接口
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();
}
}
输出:
示例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)