2 回答
TA贡献1871条经验 获得超8个赞
可以用sleep:
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();
Thread.sleep(100);
System.out.println("Hello from main Thread!");
myThread.join();
}
}
TA贡献1843条经验 获得超7个赞
public static void main(String[] args) throws InterruptedException {
Thread myThread = new Thread(){
public void run(){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Hello from new Thread!");
}
};
myThread.start();
Thread.sleep(500);
System.out.println("Hello from main Thread!");
myThread.join();
}
我把题主的yield()换成了sleep(),yield()方法只能让同优先级的线程有执行的机会。可能是主线程比子线程优先级高
添加回答
举报