【问题标题】:Call start method two times调用 start 方法两次
【发布时间】:2014-10-05 12:55:53
【问题描述】:

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

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吗?

【问题讨论】:

  • 懒惰的问题。阅读 javadoc。

标签: java multithreading


【解决方案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.

你不能启动一个线程两次。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-10-18
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 2017-10-15
      • 2011-02-09
      相关资源
      最近更新 更多