如何使用wait暂停线程并通知JavaFX

时间:2017-05-27 22:23:15

标签: java multithreading

我不清楚如何使用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
            }


        });

1 个答案:

答案 0 :(得分:0)

我会尝试给你一个简单的例子,然后尝试将它应用到你的程序......

    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();
    }
}

那就是它。我希望这能帮到你。