1

I am writing Ukelele Simulator, and I want to play a note on each string with a short delay in between. Currently, I have a method that returns an AudioClip containing the sound of the currently pressed note on each string, and I am attempting to play those AudioClips in succession with a 500 millisecond delay using Thread.sleep().

    public static void main(String[] args){
    //test it

    UkeString stringG = new UkeString('G');
    UkeString stringC = new UkeString('C');
    UkeString stringE = new UkeString('E');
    UkeString stringA = new UkeString('A');

    try{
        AudioClip G = stringG.getNoteAudio();
        AudioClip C = stringC.getNoteAudio();
        AudioClip E = stringE.getNoteAudio();
        AudioClip A = stringA.getNoteAudio();
        G.play();
        Thread.sleep(500);
        C.play();
        Thread.sleep(500);
        E.play();
        Thread.sleep(500);
        A.play();
        Thread.sleep(500);
    }
    catch(Exception e){
        System.out.println(e);
    }
    return;
}

However, I am encountering some odd irregular behavior from Thread.sleep(). Normally, when I execute the above code the first Thread.sleep() following G.play() either does not execute for the full 500 milliseconds or not at all, because the 'G' and 'C' notes are played in rapid succession. After that, the 'E' and 'A' notes will play as expected in 500 millisecond intervals.

The really weird thing is that if I run the program again before the other instance has ended (i.e. the notes in the old instance are still playing), then the new instance executes as expected with all the notes playing in 500 millisecond intervals. What's going on here?

GoatFood
  • 25
  • 1
  • 4
  • Use a `ScheduledExecutorService` or some custom scheduling code. `Thread.sleep` is *never* reliable for timing. https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html – Matt Coubrough Dec 07 '14 at 20:10

1 Answers1

1

See http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html

Your answer is here (in bold):

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

In other words, you can't have that much of a fine control with time using Thread.sleep()

toddlermenot
  • 1,588
  • 2
  • 17
  • 33
  • Thanks for the response. I saw that when searching, but I got the impression that the precision error was on the nanosecond level, rather than hundreds of milliseconds. Any suggestions for a workaround? I was unable to find anything effective. – GoatFood Dec 07 '14 at 20:12