首页 > 解决方案 > 如何在android studio中运行特定时间的线程

问题描述

我正在使用一个线程来运行我的数据库连接检查我希望这个线程运行特定的时间,我尝试使用倒数计时器类,但是没有,请提供任何帮助。

标签: javaandroidandroid-studiohandlerjava-threads

解决方案


您可以使用ExecutorService并执行以下操作:

public class ExampleClass {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(new DatabaseConnection());

        try {
            future.get(3, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            ...
        } catch (ExecutionException e) {
            ...
        } catch (TimeoutException e) {
            // do something in case of timeout
            future.cancel(true);
        }

        executor.shutdownNow();
    }
}

class DatabaseConnection implements Callable<String> {
    @Override
    public String call() throws Exception {
        while (!Thread.interrupted()) {
            // Perform your task here, e.g. connect to your database
        }
        return "Success";
    }
}

通过这种方式,您可以在另一个线程上执行任务,并具有您想要的任何超时。在上面的代码片段中,设置了三秒的超时。


推荐阅读