猿问

如何强制执行单例(一个全局实例)ScheduledExecutorService,一次一个任务?

我有一个应用程序需要从服务器请求数据,有时作为一次性请求,有时它需要以固定速率轮询。


对于一次性请求,我只使用这样的线程:


    public void request() {

        Thread requestThread = new Thread(this);

        requestThread.start();

    }

这些没关系,它们执行然后就完成了。


但是,对于长轮询任务,我似乎永远不能一次只执行其中一个。


我想要的是以下方法:


    public void longPoll() {

        try {

            pollingScheduledExecutor.scheduleAtFixedRate(this, 0, 3, TimeUnit.SECONDS);

        } catch (Exception ignored) {

        }

    }

只能存在一次,但现在发生的情况是,当我从第一堂课调用它时,它会正常开始,但在第二个任务调用后它永远不会停止。


如何强制执行只有一个全局实例 this ScheduledExecutorService?


对于上下文,这是这些方法所在的类:


public abstract class AbstractCommunicationChannel implements Runnable {

    static String SERVER_ADDRESS = "http://0.0.0.0";


    private URL url;

    private JSONObject requestObject;

    private JSONObject responseObject;


    private volatile ScheduledExecutorService pollingScheduledExecutor = Executors.newSingleThreadScheduledExecutor();


    public void longPoll() {

        try {

            pollingScheduledExecutor.scheduleAtFixedRate(this, 0, 3, TimeUnit.SECONDS);

        } catch (Exception ignored) {

        }

    }


    public void request() {

        Thread requestThread = new Thread(this);

        requestThread.start();

    }


    AbstractCommunicationChannel(URL url, JSONObject requestObject) {

        this.url = url;

        this.requestObject = requestObject;

    }


    /**

     * This is the general purpose tool for hitting the server and getting a response back.

     */

    public void run() {

        Log.i("requestObject", requestObject.toString());

        try {

            HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();

            httpUrlConnection.setDoOutput(true);

            httpUrlConnection.setRequestMethod("POST");

            httpUrlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");


            }


}


交互式爱情
浏览 128回答 1
1回答

冉冉说

又是我。如果您只想要一个正在运行的轮询任务,则必须取消前一个(如果已经存在)。例子:private static final Object lock = new Object();private static ScheduledFuture<?> currentRunningTask;&nbsp; &nbsp; public void longPoll() {&nbsp; &nbsp; &nbsp; &nbsp; synchronized (lock) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (currentRunningTask != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; currentRunningTask.cancel(true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; currentRunningTask = pollingScheduledExecutor.scheduleAtFixedRate(this, 0, 3, TimeUnit.SECONDS);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception ignored) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ignored.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答