简体   繁体   中英

how to run a thread for a specific time in android studio

I am using a thread to run my database connection checking I want this thread to run for a specific time, I tried using countdown Timer class,but that didn't,work any help please.

You can use an ExecutorService and do something like this:

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

This way you perform a task on another thread with any timeout you want. In the above code snippet a timeout of three seconds is set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM