调用启动方法两次

时间:2014-10-05 12:55:53

标签: java multithreading

为什么以下代码会抛出异常?

class MyThread extends Thread 
{
    public static void main (String [] args) 
    {
        MyThread t = new MyThread();
        t.start();
        System.out.print("one. ");
        t.start();
        System.out.print("two. ");
    }

    public void run() 
    {
        System.out.print("Thread ");
    }
}

你能指点我JLS吗?

2 个答案:

答案 0 :(得分:1)

这是start()方法的合同:

public void start()

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

Throws:
    IllegalThreadStateException - if the thread was already started.

你不能两次开始一个线程。

答案 1 :(得分:1)

正如其他回复所说,你不能两次启动线程。但是,也许您想要做的是启动2个线程:在这种情况下,只需再次实现您的线程对象:

    MyThread t = new MyThread();
    t.start();
    System.out.print("one. ");
    MyThread t2 = new MyThread();
    t2.start();
    System.out.print("two. ");