class HelloWorld {
public static void main(String[] args) throws InterruptedException {
Thread myThread = new Thread() {
public void run(){
System.out.println("Hello from new Thread!");
}
};
myThread.start();
Thread.yield();
System.out.println("Hello from main Thread!");
myThread.join();
}
}
《七周七并发模型》
作者说结果可能是
结果可能一
Hello from main Thread!
Hello from new Thread!
结果可能二
Hello from new Thread!
Hello from main Thread!
为什么我的结果只有一。
You can use sleep:
I replaced the yield() in the question with sleep(). The yield() method can only give threads with the same priority a chance to execute. It may be that the main thread has a higher priority than the child thread