【发布时间】:2017-06-13 03:34:30
【问题描述】:
我正在使用线程定期运行三秒背景动画。
我从一个用 Swing 编写的 Thread Demo 示例中改编了有问题的代码,并使用了
它取代了使用线程和任务的不太正常的早期版本。
我的程序在播放视频或运行动画时停止/暂停线程 并在结束视频或动画时启动一个新线程。这似乎没有 任何缺点,这就是为什么我很困惑为什么我之前的 JavaFX 搜索没有出现 与我正在使用的解决方案类似。这似乎是一种相当直接的跑步方法 简短的背景动画。
我在哪里做错了?我错过了什么?我将如何重写这段代码 同时使用 Thread 和 Task 还是我需要?
我应该补充一下 - while 和 run 语句与原始语句几乎没有变化 Swing 代码的唯一重要补充是添加 thread.setDaemon( true ) 开始线程()。
播客听众。
// background thread
class BackGround extends Thread {
@Override
public void run() {
while ( suspend.getValue() == false ) {
try {
int r = shared.randInt( 5, 10 );
Thread.sleep( r * 1000 );
} catch ( InterruptedException e ) {
// do nothing
}
if ( suspend.getValue() == false ) {
Platform.runLater( () -> {
int g = shared.cssGradients.length - 1;
g = shared.randInt( 0, g );
gradientColor.set( shared.cssGradients[g] );
Boolean bif = shared.updatePanes( shared.cssGradients[g],
leftPane, rightPane );
});
}
}
}
} // class background
// start thread
public synchronized void startThread() {
thread = new BackGround(); // Thread thread ...defined elsewhere
thread.setDaemon( true );
thread.start();
}
// stop thread
public synchronized void stopThread() {
suspend.set( true );
}
【问题讨论】:
标签: multithreading javafx