JavaFx:为什么剂量 'Thread.sleep( )' 停止 UI 线程?
JavaFx: Why dose 'Thread.sleep( )' stop UI threads?
public void startApp(){
primaryStage.show();
new Thread(new Runnable(){
public void run(){
Thread.sleep(20000);//2 seconds
//do something.........
System.out.println("all things done");
}
}).run();
}
我认为primaryStage会显示first.But,实际上primaryStage总是在新线程结束后显示(打印'all things done'后)。如果我删除 'Thread.sleep(20000)',primaryStage 也在 'all things done' 之后。为什么?我哪里错了吗?
先谢谢大家!
Thread.sleep(20000);//2 seconds
20秒。
我已经试过这段代码,它似乎按您预期的那样工作,所以问题一定出在其他地方。 https://ideone.com/zEjT8Q
也许你想要的是这样的:
public void startApp(){
primaryStage.show();
new Thread(new Runnable(){
@Override
public void run() {
try {
Thread.sleep(20000);//2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
//do something.........
System.out.println("all things done");
}
}).run();
}
您需要实现Runnable
的方法run()
the primaryStage always shows after the new thread finished
您没有在此处创建新话题。您只是在 Runnable 对象上调用 run()
方法。
您需要使用 .start()
而不是 .run()
才能在新线程中执行。
public void startApp(){
primaryStage.show();
new Thread(new Runnable(){
public void run(){
Thread.sleep(20000);//2 seconds
//do something.........
System.out.println("all things done");
}
}).run();
}
我认为primaryStage会显示first.But,实际上primaryStage总是在新线程结束后显示(打印'all things done'后)。如果我删除 'Thread.sleep(20000)',primaryStage 也在 'all things done' 之后。为什么?我哪里错了吗? 先谢谢大家!
Thread.sleep(20000);//2 seconds
20秒。
我已经试过这段代码,它似乎按您预期的那样工作,所以问题一定出在其他地方。 https://ideone.com/zEjT8Q
也许你想要的是这样的:
public void startApp(){
primaryStage.show();
new Thread(new Runnable(){
@Override
public void run() {
try {
Thread.sleep(20000);//2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
//do something.........
System.out.println("all things done");
}
}).run();
}
您需要实现Runnable
run()
the primaryStage always shows after the new thread finished
您没有在此处创建新话题。您只是在 Runnable 对象上调用 run()
方法。
您需要使用 .start()
而不是 .run()
才能在新线程中执行。