0

I'm working on a music player application.

I'm updating a global variable called "songPosition" inside of a thread. The problem is, whenever a song is switched, it creates a new thread, however the old one is still running in the background and also incrementing the global variable. This is causing the variable to increment quicker than I would like.

Is there a way to stop the old thread from running so that this problem doesn't persist?

Code:

private int songPosition;

new Thread(){
    public void run(){
        songPosition = 0;
        while (songPosition < songDuration){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // here is the variable being incremented
            songPosition++;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    seekBar.setProgress(songPosition); //This requires the variable to be final which is why I have a global variable
                    songPositionTextView.setText(String.valueOf(songPosition));
                }
            });
        }
    }
}.start();
Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
BlakeB9
  • 345
  • 1
  • 3
  • 13

2 Answers2

0

The songposition is local to the the current thread's context. You can use ThreadLocal variable here.

Also you can use Cancellable Tasks using Futures.

Soni
  • 142
  • 8
  • I've just read up on ThreadLocal, although it seems I'm not able to increment it or compare it. – BlakeB9 Aug 26 '20 at 06:32
0

To answer your question if you are going to share the variable amoung multiple threads then please declare that with "volatile" so that all those threads will read the latest data of that variable from its memory directly.

First you have to add the newly created thread instance into a list (If you are handling more threads) so that later point you can easily interrupt all those running threads. If you want to kill specific thread then use ConcurrentMap<String, Thread> the key might be your unique name of that thread and add it into your map.

Hakuna Matata
  • 755
  • 3
  • 13