F
F
frankie2014-06-04 18:11:15
Java
frankie, 2014-06-04 18:11:15

What are the alternatives to Thread.sleep / Timer in Java?

Good day.
I recently started learning Java. Now I am writing a synthesizer for Android, I wanted to implement an arpeggiator in it. The arpeggiator works in a separate thread as follows:
1. Scan an array of notes.
2. If the note is not equal to zero, turn it on.
3. We fall asleep for its duration.
4. Turn off the note.
5. We fall asleep for the interval between notes.
6. Move on to the next note.
In general, everything works, however, when using Sleep(), Timer() or nanoTime(), the duration of notes / intervals is not constant and changes within +/- 20 ms, which, of course, is noticeable by ear.

while(hasTouch)
{
    for (int note : sequence)
    {
        if (note != 0)
        {
            playNote(note);
            Thread.sleep(duration);
            stopNote(note);
            Thread.sleep(duration);
        }
    }
}

How can you achieve consistent and accurate intervals? What other ways are there to pause code execution for a given amount of time?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
B
bimeg, 2014-06-04
@bimeg

while (target > System.nanoTime()){}

A
anyd3v, 2014-06-04
@anyd3v

Have you tried using scheduler? And do you need to do sleep at all?
developer.android.com/reference/java/util/concurre...

R
rewlad, 2014-06-08
@rewlad

I'm not an Android expert, but the first thing I would break through:
And what kind of OS (multi-tasking, not real-time) can give time guarantees.
If there are fewer processors than processes ...
archlinux.org.ru/forum/topic/12042/?page=2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question