使用多线程在特定时间内更改javafx圈子的颜色

编程入门 行业动态 更新时间:2024-10-14 02:21:48
本文介绍了使用多线程在特定时间内更改javafx圈子的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在用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圈子的颜色

本文发布于:2023-11-27 13:31:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638279.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间内   多线程   圈子   颜色   在特定

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!