首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java启动和停止线程

Java启动和停止线程
EN

Stack Overflow用户
提问于 2018-06-12 02:56:07
回答 3查看 526关注 0票数 0

我不知道如何在Java中停止Thread

我有一个创建并启动Threadfunction。现在,当我启动程序时,我想让它启动Thread。在此之后,如果按下button,则我希望Thread停止,当再次按下button时,我希望Thread重新开始,或重新开始(无关紧要)。

我创建Threadfunction

代码语言:javascript
复制
private void startRecordingUserInput() {
    AudioDispatcher dispatcher =
            AudioDispatcherFactory.fromDefaultMicrophone(44100, 2048, 0);


    PitchDetectionHandler pdh = new PitchDetectionHandler() {
        @Override
        public void handlePitch(PitchDetectionResult res, AudioEvent e) {
            final float pitchInHz = res.getPitch();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pitchText.setText("" + pitchInHz);
                    gameView.setSingerArrowPitch(pitchInHz);
                    gameView.setCurrentTime(mid);
                    gameView.invalidate();
                }
            });
        }
    };
    AudioProcessor pitchProcessor = new PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.FFT_YIN, 44100, 2048, pdh);
    dispatcher.addAudioProcessor(pitchProcessor);

    Thread audioThread = new Thread(dispatcher, "Audio Thread");
    audioThread.start();
} 

以及我启动它并想要对Thread执行start/stop的部分。

代码语言:javascript
复制
    //Start the Thread
    startRecordingUserInput();

    playRecordButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!isPlaying){

                //Start the Thread again if it is not running or 
                //make a new one

                isPlaying = true;

            } else if(isPlaying){

                //Stop the Thread

                isPlaying = false;

            }
        }
    });
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50804364

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档