0

I have this thread.

class Hilo1 extends Thread {
            @Override
            public void run() {
                while (contador<6) {
                    try {
                        Thread.sleep(10000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
contador++;
}


                            
                        });
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

This thread finishes after a minute, because it runs every 10 seconds and it does that 6 times. When it´s done, I´d like to do some tasks, but I don´t know how to detect when it finishes. I have read about isAlive() method but my project doesn´t let me use it. I´d like to detect when it finishes so I can do the next tasks that have to be done once Hilo1 has finished. Thank you.

louisMay
  • 23
  • 3
  • Give `Hilo1` a constructor, in that constructor pass a reference to a [*callback*](https://stackoverflow.com/a/19405498/2970947). That answer is a little outdated, because Java does have functors now. – Elliott Frisch Mar 22 '23 at 16:36
  • You want to do two things. You want to make sure that thing B doesn't start until thing A is finished. In other words, you want to do the two things _sequentially._ So, why not do both of those things in the same thread? [Note: Elliott Frisch's suggestion to use a callback (see above) is just that. It's a way of doing both things in the same thread.] – Solomon Slow Mar 22 '23 at 18:56

1 Answers1

1

Provide a callback when creating your thread to determine when thread is finished.

public class Hilo1 extends Thread {

    private final Callback callback;

    private int contador = 0;

    public Hilo1(Callback callback) {
        this.callback = callback;
    }

    @Override
    public void run() {
        while (contador < 6) {
            try {
                Thread.sleep(10000);
                contador++;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        callback.call();
    }
}

interface Callback {
    void call();
}
Timur Panzhiev
  • 607
  • 6
  • 12