-1

I create an alarm clock that rings an alarm until the puzzle is solve I have a play class that play alarm ` package clock;

import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
import javax.swing.*;


public class Play {
AudioClip ac;
Thread t;
public void playSound(int n)
{
     try {
        URL url = new URL("file:1.wav" );
        ac = Applet.newAudioClip(url);
        t= new Thread(){
            public void run(){
                ac.loop();
            }
        };
        if(n==0){
            t.start();
        }
        if (n==1){
            JOptionPane.showMessageDialog(null,"OFF");
            ac.stop();
            t.interrupt();
        }
    } 
     catch (Exception e) {
        JOptionPane.showMessageDialog(null,e); 
    }
}`

it play alarm on time but when i call it with parameter 1 it shows "OFF" but alarm thread is not stop

Braj
  • 46,415
  • 5
  • 60
  • 76
user3392409
  • 77
  • 1
  • 4

2 Answers2

1

I create an alarm clock that rings an alarm until the puzzle is solve

You can try with Swing Timer that is most suitable for swing application.

Read more How to Use Swing Timers


Play sound at fix interval and stop the timer once puzzle is solved. Just set the flag isSolved to true and swing timer will be stopped.

Sample code:

private Timer timer;
private volatile boolean isSolved;
...

// interval of 1 second
timer = new javax.swing.Timer(1000, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {

        if(isSolved){
           // stop the timer
            timer.stop();
        }else{
            // play sound
        }
    }
});
timer.setRepeats(true); // you can turn off it 
timer.start();
Braj
  • 46,415
  • 5
  • 60
  • 76
-1

In your code for the thread add a bolean value running, and when run() is called set it to true. Create an additional method, stopRun() and use this to stop the thread.

    Thread thread = new Thread(new Runnable(){

        private bolean run;

        public void run(){
           while(run){
               //code
            }
        }

  public void stopRun(){
      this.run = false;
    }
  }
);
Confuto
  • 281
  • 2
  • 13