run In Thread - Java java.lang

Java examples for java.lang:Thread

Description

run In Thread

Demo Code


//package com.java2s;
import java.util.concurrent.atomic.AtomicReference;

public class Main {
    public static void runInThread(final Runnable runnable) {
        final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
        Runnable exceptionGuard = new Runnable() {
            @Override/*ww  w  . ja  v a2  s.  c  o m*/
            public void run() {
                try {
                    runnable.run();
                } catch (Throwable thr) {
                    exception.set(thr);
                }
            }
        };
        run(exceptionGuard);
        if (exception.get() != null) {
            throw new RuntimeException("Caught exception in thread",
                    exception.get());
        }
    }

    private static void run(Runnable runnable) {
        Thread thread = startDaemonThread(runnable);
        try {
            thread.join();
        } catch (InterruptedException ie) {
            throw new RuntimeException(ie);
        }
    }

    private static Thread startDaemonThread(Runnable runnable) {
        Thread result = new Thread(runnable);
        result.setDaemon(true);
        result.start();
        return result;
    }
}

Related Tutorials