user1656546
user1656546

Reputation: 93

Java scheduleAtFixedDelay stop

how can i make such code working?

public void start()
{
    ThreadPoolManager.getInstance().scheduleWithFixedDelay(new Thread(), 1000, 1000);
}

public class Thread implements Runnable
{
    int i = 0;
    @Override
    public void run()
    {
        i++;
        if(i==5)
            //TODO stop this thread
    }
}

I want to stop the Thread after i == 5

Edit: It can be done like that:

public void start()
{
    ThreadPoolManager.getInstance().schedule(new Thread(), 1000);
}

public class Thread implements Runnable
{
    int i = 0;
    @Override
    public void run()
    {
        while(i!=5)
        {
            i++;
            try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
        }
    }
}

But still if anybody have idea how to make it with scheduleWithFixedDelay i would be glad to know the answer :)

Upvotes: 1

Views: 414

Answers (2)

Tudor
Tudor

Reputation: 62469

Stopping a ScheduledThreadPoolExecutor task from within itself is a bit more convoluted. You could try to pass back the ScheduledFuture to the task itself and call cancel (not thread-safe but since you have a delay of 1000 ms it should be enough):

public void start()
{
    Task t = new Task();
    ScheduledFuture sf = ThreadPoolManager.getInstance().scheduleAtFixedDelay(t, 1000, 1000);
    t.setFuture(sf);
}

class Task implements Runnable {

    private int i = 0;
    private ScheduledFuture sf;

    public void setFuture(ScheduledFuture sf) {
        this.sf = sf;
    }

    public void run() {
        i++;
        if(i==5)
            sf.cancel(true);
    }
}

Upvotes: 1

tckmn
tckmn

Reputation: 59363

You could just use this.stop().

Edit: didn't notice it would keep FixedDelay-ing, so:

public void start()
{
    ThreadPoolManager.getInstance().scheduleAtFixedDelay(new Thread(new MyThread()), 1000, 1000);
}

public class MyThread implements Runnable
{
    int i = 0;
    boolean keepGoing = true;
    @Override
    public void run()
    {
        if (keepGoing)
        {
            i++;
            System.out.println("Thread in " + i);
            if(i==5)
                keepGoing = false;
        }
    }
}

Upvotes: 0

Related Questions