Java Thread Executor Execute executeForever(final Runnable runnable)

Here you can find the source of executeForever(final Runnable runnable)

Description

execute Forever

License

Apache License

Parameter

Parameter Description
runnable a parameter

Declaration

@Deprecated
public static Future<?> executeForever(final Runnable runnable) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;

public class Main {
    /**/*from   ww  w  .  j av a  2  s.c o m*/
     * @deprecated Should be using worker threads for everything really
     * @param runnable
     * @return
     */
    @Deprecated
    public static Future<?> executeForever(final Runnable runnable) {
        final AtomicBoolean keepRunning = new AtomicBoolean(true);
        final Future<?> future = Executors.newFixedThreadPool(1).submit(new Runnable() {
            public void run() {
                while (keepRunning.get()) {
                    runnable.run();
                }
            }
        });

        Future<?> realFuture = new Future<Object>() {
            public boolean cancel(boolean mayInterruptIfRunning) {
                keepRunning.set(false);
                return future.cancel(mayInterruptIfRunning);
            }

            public boolean isCancelled() {
                return future.isCancelled();
            }

            public boolean isDone() {
                return future.isDone();
            }

            public Object get() throws InterruptedException, ExecutionException {
                return future.get();
            }

            public Object get(long timeout, TimeUnit unit)
                    throws InterruptedException, ExecutionException, TimeoutException {
                return get(timeout, unit);
            }

        };

        return realFuture;

    }
}

Related

  1. execute(Runnable task)
  2. execute(Runnable task)
  3. execute(String name, Runnable runnable)
  4. executeAndWait(final Runnable r)
  5. executeAsynchronously(Runnable r)
  6. executeFuture(Callable callable)
  7. executeInCachedPool(Runnable runnable)
  8. executeInThread(Runnable r)
  9. executeInThreadPool(Runnable runnable)