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 :)

Answers


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);
    }
}

Need Your Help

Google Docs web UI warns automatic document upgrade (from Writely to KIX) will soon be done. Is it safe and well prepared for developers?

google-docs-api

Google Docs web UI warns "This document will soon be upgraded to the latest version of Google documents" when a user opens a Writely document.

exchange data within objects (widgets) in python (using pyqt)

python oop pyqt pyqt4

I am having difficulties with finding the solution to the following problem. Here is the main file:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.