1

我怎样才能使这样的代码工作?

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 == 5 之后停止线程

编辑:可以这样做:

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

但是,如果有人知道如何使用 scheduleWithFixedDelay 来实现它,我会很高兴知道答案:)

4

2 回答 2

1

从内部停止ScheduledThreadPoolExecutor任务有点复杂。您可以尝试将其传递回ScheduledFuture任务本身并调用cancel(不是线程安全的,但由于您有 1000 毫秒的延迟,因此应该足够了):

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);
    }
}
于 2012-09-08T13:16:41.887 回答
0

你可以只使用this.stop().

编辑:没有注意到它会保持 FixedDelay-ing,所以:

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;
        }
    }
}
于 2012-09-08T13:15:18.710 回答