我正在用javafx创建交通信号灯模拟器,它使用多线程概念每2秒更改一次颜色(第一个红灯闪烁并保持2秒).我有我的代码如下.但是它没有按预期工作.它只会闪烁所有指示灯,直到有人可以帮我弄清楚我出了什么问题吗?谢谢
I am creating traffic light simulator with javafx that changes colour in every 2 seconds (first red light blinks and remain for 2 seconds) using the concept of multithreading. I have my code as given below. But it doesn't work as expected. It just blinks all light and sto Can somebody help me figure it out where I went wrong? Thanks
public void startThreads() throws InterruptedException { Runnable taskOne = new Runnable(){ @Override public void run(){ try { Platform.runLater(new Runnable() { @Override public void run() { circle.setFill(Color.RED); circle1.setFill(Color.GREY); circle2.setFill(Color.GREY); } }); Thread.currentThread().sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }; Runnable taskTwo ...... Runnable taskThree ..... Thread thread1 = new Thread(taskOne); Thread thread2 = new Thread(taskTwo); Thread thread3 = new Thread(taskThree); //Start thread 1 thread1.start(); thread1.join(); //start thread 2 thread2.start(); thread2.join(); //Start thread 3 thread3.start(); thread3.join(); }推荐答案
来自 Thread.join
等待该线程死亡.
Waits for this thread to die.
这是
thread1.start(); thread1.join();与
相比,没有提供任何好处
doesn't provide any benefits compared to
taskOne.run();因为这会停止执行调用join的方法,直到Thread完成.
since this stops the execution of the method invoking join until the Thread completes.
通过使用Timeline,可以以一种更加优雅的方式实现您要执行的操作:
It's possible to achieve what you're trying to do in a much more elegant way by using Timeline:
Timeline timeline = new Timeline( new KeyFrame(Duration.ZERO, evt -> { circle.setFill(Color.RED); circle1.setFill(Color.GREY); circle2.setFill(Color.GREY); }), new KeyFrame(Duration.seconds(2), evt -> { // TODO: GUI modifications for second state }), new KeyFrame(Duration.seconds(4), evt -> { // TODO: GUI modifications for third state }) ); timeline.play();您可能需要调整第三个KeyFrame的持续时间. Duration参数指定从动画开始开始的时间. EventHandler<ActionEvent>在JavaFX应用程序线程上执行,并且不能包含长时间运行的代码,例如Thread.sleep.您可能需要添加其他KeyFrame.
You may need to adjust the duration for the third KeyFrame. The Duration parameter specifies the time from the beginning of the animation. The EventHandler<ActionEvent>s are executed on the JavaFX application thread and must not contain long-running code such as Thread.sleep. You may need to add additional KeyFrames.
更多推荐
使用多线程在特定时间内更改javafx圈子的颜色
发布评论