早上无事看到这个:
public static void main(String[] args)throws InterruptedException{
Thread t = new Thread(new MyThread2());
t.start();
System.out.print("main1");
t.join();
System.out.print("main2");
}
@Override
public void run() {
System.out.print("run1");
System.out.print("run2");
}
}
因为join(),main2肯定最后打印;
run1 run2 打印顺序固定为:run1,run2;
-
主要有点疑惑,main1,和run里面的到底谁先打印?
run()
method of * the receiver will be called by the receiver Thread itself (and not the * Thread callingstart()
). * * @throws IllegalThreadStateException - if this thread has already started. * @see Thread#run */ public synchronized void start() { checkNotStarted();hasBeenStarted = true; nativeCreate(this,stackSize,daemon);
}
看到start里的native开头,我就GG了。但是我知道,Thread的start不会阻塞主线程的运行,所以main1打印最先。
然后,敲代码多次运行验证:
G:\java>javac MyThread2.java
G:\java>java MyThread2
main1run1run2main2
原文链接:https://www.f2er.com/note/422302.html