Example usage for java.lang Runnable run

List of usage examples for java.lang Runnable run

Introduction

In this page you can find the example usage for java.lang Runnable run.

Prototype

public abstract void run();

Source Link

Document

When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.

Usage

From source file:com.willwinder.universalgcodesender.utils.GUIHelpers.java

/**
 * Displays an error message to the user.
 * @param errorMessage message to display in the dialog.
 * @param modal toggle whether the message should block or fire and forget.
 *//*from  www .  java2s.  c  om*/
public static void displayErrorDialog(final String errorMessage, boolean modal) {
    if (StringUtils.isEmpty(errorMessage)) {
        LOGGER.warning("Something tried to display an error message with an empty message: "
                + ExceptionUtils.getStackTrace(new Throwable()));
        return;
    }

    Runnable r = () -> {
        //JOptionPane.showMessageDialog(new JFrame(), errorMessage, 
        //        Localization.getString("error"), JOptionPane.ERROR_MESSAGE);
        NarrowOptionPane.showNarrowDialog(250, errorMessage.replaceAll("\\.\\.", "\\."),
                Localization.getString("error"), JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
    };

    if (modal) {
        r.run();
    } else {
        java.awt.EventQueue.invokeLater(r);
    }
}

From source file:Main.java

public static Handler runInUIThread(final Runnable runnable, boolean runImmediatelyIfPossible) {
    if (runnable == null) {
        return null;
    }/*from  ww w  . ja  v  a2  s .  c  o m*/

    final Handler handler;
    Looper mainLooper = Looper.getMainLooper();
    if (runImmediatelyIfPossible && (Thread.currentThread() == mainLooper.getThread())) {
        handler = null;
        runnable.run();
    } else {
        handler = new Handler(mainLooper);
        handler.post(runnable);
    }

    return handler;
}

From source file:Main.java

/**
 * Causes <code>runnable</code> to have its <code>run</code> method called
 * in the dispatch thread of {@link Toolkit#getSystemEventQueue the system
 * EventQueue} if this method is not being called from it. This will happen
 * after all pending events are processed. The call blocks until this has
 * happened. This method will throw an Error if called from the event
 * dispatcher thread./*ww  w.  j  av a2s.  c  o  m*/
 * 
 * @param runnable
 *            the <code>Runnable</code> whose <code>run</code> method should
 *            be executed synchronously on the <code>EventQueue</code>
 */
public static void invokeOnEdtAndWait(Runnable runnable) {
    boolean isEdt = EventQueue.isDispatchThread();
    if (!isEdt) {
        try {
            EventQueue.invokeAndWait(runnable);
        } catch (InterruptedException e) {
            System.err.println("EDT task interrupted");
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            System.err.println("EDT task invocation exception");
            e.printStackTrace();
        }
    } else {
        runnable.run();
    }
}

From source file:org.kaaproject.kaa.client.logging.DefaultLogCollectorTest.java

@BeforeClass
public static void beforeSuite() {
    executorContext = Mockito.mock(ExecutorContext.class);
    executor = Executors.newSingleThreadScheduledExecutor();
    Mockito.when(executorContext.getApiExecutor()).thenReturn(new AbstractExecutorService() {

        @Override//  ww w  . ja v  a2 s  .co  m
        public void execute(Runnable command) {
            command.run();
        }

        @Override
        public List<Runnable> shutdownNow() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public void shutdown() {
            // TODO Auto-generated method stub

        }

        @Override
        public boolean isTerminated() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean isShutdown() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
            // TODO Auto-generated method stub
            return false;
        }
    });
    Mockito.when(executorContext.getCallbackExecutor()).thenReturn(executor);
    Mockito.when(executorContext.getScheduledExecutor()).thenReturn(executor);
}

From source file:Main.java

/**
 * Add an OnGlobalLayoutListener for the view.
 * This is just a convenience method for using {@code ViewTreeObserver.OnGlobalLayoutListener()}.
 * This also handles removing listener when onGlobalLayout is called.
 *
 * @param view     the target view to add global layout listener
 * @param runnable runnable to be executed after the view is laid out
 *//*from   w w w  . j  a va 2 s. c  o m*/
public static void addOnGlobalLayoutListener(final View view, final Runnable runnable) {
    ViewTreeObserver vto = view.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            runnable.run();
        }
    });
}

From source file:ir.rasen.charsoo.controller.image_loader.core.LoadAndDisplayImageTask.java

static void runTask(Runnable r, boolean sync, Handler handler, ImageLoaderEngine engine) {
    if (sync) {/*from  ww w.  j a v  a2 s .  c om*/
        r.run();
    } else if (handler == null) {
        engine.fireCallback(r);
    } else {
        handler.post(r);
    }
}

From source file:Main.java

/**
 * Runs a piece of code after the next layout run
 * //  ww  w  .  j a v  a 2s.  c o  m
 * @param view The {@link View} used.
 * @param runnable The {@link Runnable} used after the next layout run
 */
@SuppressLint("NewApi")
public static void doAfterLayout(final View view, final Runnable runnable) {
    final OnGlobalLayoutListener listener = new OnGlobalLayoutListener() {
        @SuppressWarnings("deprecation")
        @Override
        public void onGlobalLayout() {
            /* Layout pass done, unregister for further events */
            if (hasJellyBean()) {
                view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            } else {
                view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
            runnable.run();
        }
    };
    view.getViewTreeObserver().addOnGlobalLayoutListener(listener);
}

From source file:Main.java

public static void createNonCancellableAcceptOrCancelDialog(Context context, String title, String message,
        String acceptButtonText, String cancelButtonText, final Runnable onAccept, final Runnable onCancel) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setCancelable(false);// w w  w .  j a v a2s.co m
    builder.setTitle(title);
    builder.setMessage(message);
    builder.setInverseBackgroundForced(true);
    builder.setPositiveButton(acceptButtonText, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            if (onAccept != null)
                onAccept.run();
        }
    });

    builder.setNegativeButton(cancelButtonText, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            if (onCancel != null)
                onCancel.run();
        }
    });
    AlertDialog alert = builder.create();
    alert.setOnKeyListener(new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_SEARCH && event.getRepeatCount() == 0) {
                return true; // Pretend we processed it
            }
            return false; // Any other keys are still processed as normal
        }
    });
    alert.show();
}

From source file:Main.java

/**
 * Add an OnGlobalLayoutListener for the view.
 * <p>This is just a convenience method for using {@code ViewTreeObserver.OnGlobalLayoutListener()}.
 * This also handles removing listener when onGlobalLayout is called.</p>
 *
 * @param view     The target view to add global layout listener.
 * @param runnable Runnable to be executed after the view is laid out.
 *//*from w  ww . ja v  a 2 s .co m*/
public static void addOnGlobalLayoutListener(final View view, final Runnable runnable) {
    ViewTreeObserver vto = view.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @SuppressWarnings("deprecation")
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            runnable.run();
        }
    });
}

From source file:fi.luontola.cqrshotel.framework.EventStoreContract.java

private static void repeatInParallel(int iterations, Runnable task, Runnable invariantChecker)
        throws Exception {
    final int PARALLELISM = 10;
    ExecutorService executor = Executors.newFixedThreadPool(PARALLELISM + 1);
    Future<?> checker;//from   w w  w. j  av a 2s  .co  m
    try {
        checker = executor.submit(() -> {
            while (!Thread.interrupted()) {
                invariantChecker.run();
                Thread.yield();
            }
        });
        List<Future<?>> futures = new ArrayList<>();
        for (int i = 0; i < iterations; i++) {
            futures.add(executor.submit(task));
        }
        for (Future<?> future : futures) {
            // will throw ExecutionException if there was a problem
            future.get();
        }
    } finally {
        executor.shutdownNow();
        executor.awaitTermination(10, TimeUnit.SECONDS);
    }
    // will throw ExecutionException if there was a problem
    checker.get(10, TimeUnit.SECONDS);
}