Always spawn a new, non-UI thread process to execute ACTION - Android java.lang

Android examples for java.lang:Thread

Description

Always spawn a new, non-UI thread process to execute ACTION

Demo Code


//package com.java2s;

public class Main {
    /**//from   www  .java 2  s.c  o  m
     * Same as calling #runOnNewThread( action, false )
     */
    public static void runOnNewThread(final Runnable action) {
        runOnNewThread(action, false);
    }

    /**
     * Always spawn a new, non-UI thread process to execute ACTION
     *
     * @param action procedure to run on the new Thread
     * @param wait   true if we should wait for action to complete before returning to calling process
     */
    public static void runOnNewThread(final Runnable action,
            final boolean wait) {
        final Runnable threadRunnable = new Runnable() {
            @Override
            public void run() {
                synchronized (this) {
                    action.run();
                    if (wait) {
                        this.notify();
                    }
                }
            }
        };

        synchronized (threadRunnable) {
            new Thread(threadRunnable).start();
            waitForAction(threadRunnable, wait);
        }
    }

    protected static void waitForAction(final Runnable action, boolean wait) {
        if (wait) {
            synchronized (action) {
                try {
                    action.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Related Tutorials