Java主线程与用户创建线程的执行顺序为何不符合预期?
为什么主线程先输出等待信息,子线程才开始打印内容?
先看下你提供的测试代码:
public class SimpleThreads { // Display a message, preceded by the name of the current thread static void threadMessage(String message) { String threadName = Thread.currentThread().getName(); System.out.format("%s: %s%n", threadName, message); } private static class MessageLoop implements Runnable { public void run() { String importantInfo[] = { "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too" }; try { for (int i = 0; i < importantInfo.length; i++) { threadMessage(importantInfo[i]); } } catch (Exception e) { threadMessage("I wasn't done!"); } } } public static void main(String args[]) throws InterruptedException { threadMessage("Starting MessageLoop thread"); Thread t = new Thread(new MessageLoop()); t.start(); threadMessage("Waiting for MessageLoop thread to finish"); } }
运行输出:
OUTPUT main: Starting MessageLoop thread main: Waiting for MessageLoop thread to finish Thread-0: Mares eat oats Thread-0: Does eat oats Thread-0: Little lambs eat ivy Thread-0: A kid will eat ivy too
这其实是操作系统的线程调度机制在起作用,咱们直白点拆解:
- 当你调用
t.start()时,只是给JVM打了个招呼:“把这个线程加到可执行队列里”,但它不会立刻抢到CPU资源开始执行——线程调度权完全在操作系统手里,这个“排队+分配CPU”的过程哪怕再快,也需要一点点时间。 - 而主线程在调用
t.start()之后,根本不会停下来等子线程启动,它会马不停蹄地执行下一行代码threadMessage("Waiting for MessageLoop thread to finish"),这行代码执行速度极快,所以自然先输出了这句。 - 等操作系统终于把CPU时间片分给Thread-0的时候,它才会启动
run()方法里的逻辑,开始打印那些句子。
简单总结:start()不是“立刻执行子线程”,而是“允许子线程被执行”,主线程会继续自己的流程,谁先抢到CPU谁先输出。
内容的提问来源于stack exchange,提问作者user1608411
相关产品推荐
相关产品推荐

