何时创建线程?

时间:2019-06-25 01:33:25

标签: java multithreading

我对线程有疑问。这是我的代码:

public class Threads {

    public static void main(String[] args) {
        NewThread nt1 = new NewThread("One");
        NewThread nt2 = new NewThread("Two");
        NewThread nt3 = new NewThread("Three");

        // Start threads
        nt1.t.start();
        nt2.t.start();
        nt3.t.start();

        try {
            // Waiting for the remaining threads to finish
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted main thread");
        }
        System.out.println("End main thread");
    }
}

//Creating many threads
class NewThread implements Runnable {

    String name;
    Thread t;

    NewThread(String threadname) {
        name = threadname;
        t = new Thread(this, name);
        System.out.println("New thread " + t);
    }

    @Override
    public void run() {
        try {
            for(int i = 5; i > 0; i--) {
                System.out.println(name + ": " + i);
                Thread.sleep(1000);
            }

        } catch(InterruptedException e) {

            System.out.println("Interrupted " + name);
        }
        System.out.println("Ending: " + name);
    }
}

真正在何时创建线程?当我创建对象NewThread并将其引用分配给main方法中类型为nt1的{​​{1}}变量时,这是一行吗?

NewThread

也许是在nt1 = new NewThread("One"); 构造函数中真正创建了线程?当我创建对象NewThread并将其引用分配给变量Thread

t

如果这个问题很愚蠢,我事先表示歉意,但是好奇心盛行。

0 个答案:

没有答案