title: Java Start and Stop Threads
body: <p>I cannot figure out how to stop a <code>Thread</code> in <code>Java</code>.</p>
  
  <p>I have a <code>function</code> that creates the <code>Thread</code> and starts it. Now when I start the program, I want it to start the <code>Thread</code>. After that if the <code>button</code> is pressed then I want the <code>Thread</code> to stop and when the <code>button</code> is pressed again, I want the <code>Thread</code> to start over, or resume (it does not matter).</p>
  
  <p>My <code>function</code> that creates the <code>Thread</code>:</p>
  
  <pre><code>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();
  } 
  </code></pre>
  
  <p>And the part where I start it and want to <code>start/stop</code> the <code>Thread</code>.</p>
  
  <pre><code>    //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;
  
              }
          }
      });
  </code></pre>