1

In Java if I have a class that creates threads from the constructor (by calling some functions of that class) and I create an object of that class in my main method. Does the main method wait until all the threads are done or does it continue to the next line?

for example:

public static void main(String[] args)  {
    WorksWithThreads obj = new WorksWithThreads ( );

    //does something else - does this line happen after all the 9 threads finished their job? 
}

class WorksWithThreads(){
    public WorksWithThreads(){
        for(int i=0;i<9;i++)
            WithThread tread= new WithThread();
    }

    private static class WithThread extends Thread {

        public WithThread () {
            run();
        }

        public void run(){
            //does something
        }
    }

}

I hope I was not too confusing.. Thank you in advance.. Shiran

4

3 回答 3

3

如果您实际上产生了新线程,您的 main 方法将在完成产生后立即继续(但在线程结束之前,假设它们运行了一段时间)

但是你没有产生线程。您正在创建 Thread 类的实例。要真正产生新线程,您必须调用 start。像你一样调用 run() 只是一个普通的方法调用,处理只会在它完成后继续。

您可能需要完成有关此主题的官方教程

于 2013-05-07T18:47:04.203 回答
1

不,线程的关键在于它们不会停止生成它们的线程的执行。main()一旦WorksWithThreads完成所有线程的生成,将继续执行,但它生成的线程将与main.

于 2013-05-07T18:43:03.810 回答
0

是的,它将在创建 9 个线程后运行。在这里你甚至还没有启动这 9 个线程。所以在它们执行之前,将执行 main 中的下一行

于 2013-05-07T18:47:26.710 回答