gpt4 book ai didi

java - 如何使用 wait 和 notification JavaFX 暂停线程

转载 作者:太空宇宙 更新时间:2023-11-04 11:27:11 25 4
gpt4 key购买 nike

我不清楚如何使用wait()和notify()来暂停线程。我读过有关同步的讨论,但我不确定如何在我的实例中进行同步。我有一个带有进度条的音乐播放器,我想在其中暂停线程以控制进度条与音乐的同步。这是我要暂停的线程:

@FXML private void clickedButton(ActionEvent event){
shuffle.setOnAction(e -> {


artistPane.setText(model.getCurrentSong());


if(firstTime){
//Multithreading with JavaFX. Essentially this other thread will check the slider to make sure its on track.
sliderThread = new Task<Void>() {

@Override
protected Void call() throws Exception {
boolean fxApplicationThread = Platform.isFxApplicationThread();
System.out.println("Is call on FXApplicationThread: " + fxApplicationThread);


//this is an infinite loop because now I only need to make this thread once, pausing and starting it, as opposed to making many threads
for(;;){
Thread.sleep(100);
progressBar.setValue(controller.getPercentageDone());

}


}

};

new Thread(sliderThread).start();
firstTime = false;
}else if(!model.getIsPlaying()){

//I want to start the thread here

}

controller.shuffle(); //this will start the music on the next song
});

这是后半部分,我也想暂停并启动线程:

play.setOnAction(e -> {

controller.play(); //this will pause/start the music

if(!model.getIsPlaying()){
//where I want to pause the thread.
}else{
//I want to start the thread here
}


});

最佳答案

我将尝试给您提供简单的示例,然后您尝试将其应用到您的程序中...

    public class TestClass extends JPanel {

/**
*
*/
private static final long serialVersionUID = 1L;
private Thread playThread ;

TestClass() {

playThread = new Thread(new Runnable() {

@Override
public void run() {
System.out.println("DO SOME THING HERE");
System.out.println("SONG WILL PLAY.....");


}
});
}

public void startMyPlayer() {
System.out.println("PLAYING NOW...");
playThread.start();
}

public void pauseMyPlayer() throws InterruptedException {
System.out.println("PAUSED NOW...");
playThread.wait();
}

public void resumeMyPlayer() {
System.out.println("RESUMING NOW...");
playThread.notify();
}
}

就是这样,希望对你有帮助。

关于java - 如何使用 wait 和 notification JavaFX 暂停线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44222134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com