Block Runnable until completion

I am using Runnable as a loop in Android. Like this:

    Timer timer = new Timer();
    timer.schedule(new looper(m_mainView, this),0, Rate);

which starts every millisecond "Rate".

Petler is the following:

class looper extends TimerTask
{
    private ImageView img;
    Context c;


    public looper(ImageView imgView, Context context)
    {
        this.img = imgView;
        this.c = context;
    }

    public void run()
    {   
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
....

I would like to lock the code inside run()until it is completed, so if it is called before completion, the thread that calls will return and end.

I tried an approach synchronized(Object)inside run()that didn't work. Also tried Mutex, which also didn't work.

Reference:)

0
source share
3 answers

looper timer.schedule, run, timer.schedule. run , , , run , , .

:

  • run , , , run , .
  • , . .

1:

class Looper extends TimerTask {
  // ** Add this **
  volatile boolean running = false;

  public Looper() {
  }

  @Override
  public void run() {
    // ** Add this **
    if (!running) {
      running = true;
      try {
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
          }

        });
        // ** Add this **
      } finally {
        running = false;
      }

    }
  }

}

:

timer.schedule(new looper(m_mainView, this, Rate),new Date());
...
class Looper extends TimerTask {
  final long rate;
  final Looper looper;

  public Looper(long rate) {
    this.rate = rate;
    looper = this;
    // ...
  }

  @Override
  public void run() {
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        // ...
        new Timer().schedule(looper, new Date(new Date().getTime() + rate));
      }

    });

  }

}
+1

synchronized :

public synchronized void run()
0

, , run ? , . -, TimerTask ScheduledExecutorService. , . , -, ScheduledFuture , , , ( ScheduledFuture get()). Java Concurrency ...

0

Source: https://habr.com/ru/post/1677439/


All Articles