Java Thread start()方法

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类 下一篇:无