user3562657
user3562657

Reputation: 167

Java Thread() sleep issues

I'm trying to add a metronome to a program and here's the class for it

public void playMet() throws IOException
    {
        int tempo = Integer.parseInt(met_speed.getText());
        //tempo = 60/tempo;
        double delay = 60/tempo*1000; 
        Thread t = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                while(Play.isSelected()){



                        try {
                            playSound("Click1.wav");
                            System.out.println("beep");
                            Thread.sleep((long) delay);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }



                }
            }
        });
        t.start();
    }

If I set the value to 60bpm, or once per second, the program works fine. If I set it to anything else, it ignores the sleep. The "system.out.println.." is there for testing, and playSound is a class that plays the wav file.

Not sure if I'm overlooking something obvious or if I'm off track to what I should be doing

Upvotes: 0

Views: 152

Answers (2)

Dmytro Melnychuk
Dmytro Melnychuk

Reputation: 2504

I recommend you to use the following methods of delay:

`
TimeUnit.NANOSECONDS.sleep(100);
TimeUnit.MICROSECONDS.sleep(100);
TimeUnit.MILLISECONDS.sleep(100);
TimeUnit.SECONDS.sleep(100);
TimeUnit.MINUTES.sleep(100);
TimeUnit.HOURS.sleep(100);
TimeUnit.DAYS.sleep(100);`

These methods are easy for using and I'm using it too without multiply the 1000.

;)

Upvotes: 2

Savvas Dalkitsis
Savvas Dalkitsis

Reputation: 11592

You are doing integer division

double delay = 60/tempo*1000;

So if you set tempo to be 100, 60/100 is 0. Your sleep will always be 0 for values greater than 60

You should try:

double delay = 60.0 / tempo * 1000.0;

Upvotes: 4

Related Questions