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.drunkendev.io.recurse.tests.RecursionTest.java

/**
 * Used to perform a timed average of a repeated set of runs.
 *
 * @param   count//from  w  ww  .  j av a  2  s .c o  m
 *          Amount of times to run {@code r}.
 * @param   r
 *          {@link Runnable} object to perform tests against.
 */
public void averageTest(int count, Runnable r) {
    Duration total = Duration.ZERO;
    for (int i = 0; i < count; i++) {
        total = total.plus(time(() -> r.run()));
    }
    System.out.format("%nAverage duration: %s%n%n", total.dividedBy(count));
}

From source file:com.thoughtworks.go.server.service.UserService.java

public void withEnableUserMutex(Runnable runnable) {
    synchronized (enableUserMutex) {
        runnable.run();
    }
}

From source file:com.futureplatforms.kirin.extensions.databases.DatabasesBackend.java

protected void executeEndTransaction(DBTransaction tx, Runnable job) {
    Executor executor = tx.mReadOnly ? mReadOnlyExecutor : mWritingExecutor;
    if (executor != null) {
        executor.execute(job);/* w  w  w . java  2 s .  co m*/
    } else {
        job.run();
    }

}

From source file:pipeline.GUI_utils.XYScatterPlotView.java

public void setWindowTitle(String title) {
    this.windowTitle = title;
    if (windowWithGraph != null) {
        Runnable r = () -> windowWithGraph.setTitle(title);
        if (java.awt.EventQueue.isDispatchThread())
            r.run();
        else/* w ww  . j  a v a  2 s.  c o  m*/
            javax.swing.SwingUtilities.invokeLater(r);
    }
}

From source file:com.auth0.api.authentication.AuthenticationAPIClientTest.java

@Before
public void setUp() throws Exception {
    mockAPI = new AuthenticationAPI();
    final String domain = mockAPI.getDomain();
    Auth0 auth0 = new Auth0(CLIENT_ID, domain, domain);
    Handler handler = mock(Handler.class);
    doAnswer(new Answer() {
        @Override//  w w w  . j  a v a2 s. c  om
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Runnable runnable = (Runnable) invocation.getArguments()[0];
            runnable.run();
            return null;
        }
    }).when(handler).post(any(Runnable.class));
    client = new AuthenticationAPIClient(auth0, handler);
}

From source file:de.codesourcery.flocking.ui.NumberInputField.java

/**
 * To be invoked when this input components
 * underlying {@link IModel} has changed
 * and thus this component needs repainting.
 *///ww  w. j  a va 2  s .c om
public void modelChanged() {

    final Number n = model.getObject();

    final int sliderValue = calcSliderValue(n);

    final Runnable r = new Runnable() {

        @Override
        public void run() {
            selfTriggeredEvent = true;
            slider.setValue(sliderValue);
            textField.setText(numberToString(n));
            selfTriggeredEvent = false;
        }
    };

    if (SwingUtilities.isEventDispatchThread()) {
        r.run();
    } else {
        try {
            SwingUtilities.invokeAndWait(r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.workplacesystems.utilsj.threadpool.WorkerThread.java

@Override
public void run() {
    while (running) {
        Runnable _runnable = null;
        synchronized (this) {
            while (running && runnable == null) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                } // Ignore, as interrupts are not used by the pool itself
            }/*from  w w  w. ja  v a 2 s  . c o  m*/
            _runnable = runnable;
        }

        if (_runnable != null) {
            try {
                _runnable.run();
            } catch (Exception e) {
                log.error("", e);
            } finally {
                synchronized (this) {
                    if (syncObject != null) {
                        synchronized (syncObject) {
                            syncObject.notify();
                        }
                    }
                    reset();
                    returnToPool();
                }
            }
        }
    }
}

From source file:edu.stanford.nlp.parser.ensemble.Ensemble.java

public void run() throws IOException {
    List<Runnable> jobs = createJobs();

    boolean multiThreaded = false;
    if ((run.equalsIgnoreCase(Const.RUN_TRAIN) && multiThreadTrain)
            || (run.equalsIgnoreCase(Const.RUN_TEST) && multiThreadEval)) {
        multiThreaded = true;//from   w w  w.j a va2s  .  co  m
    }

    String file_name;
    String phase_name;

    // reverse the training corpus
    if (run.equals(Const.RUN_TRAIN)) {
        file_name = trainCorpus;
        phase_name = "training";
    } // reverse the testing corpus
    else if (run.equals(Const.RUN_TEST)) {
        file_name = testCorpus;
        phase_name = "testing";
    } else {
        throw new RuntimeException("Unknown run mode: " + run);
    }

    if (rightToLeft) {
        File f = new File(file_name);
        File f1 = new File(workingDirectory + File.separator + f.getName());
        f1.deleteOnExit();
        FileUtils.copyFile(f, f1);

        if (rtl_pseudo_projective && run.equals(Const.RUN_TRAIN)) {
            String ppReversedFileName = workingDirectory + File.separator + f.getName() + ".pp";
            try {
                SystemLogger.logger().debug(
                        "Projectivise reversing " + phase_name + " corpus to " + ppReversedFileName + "\n");
                String input = f.getName();
                f = new File(ppReversedFileName);
                String output = f.getName();
                ProjectivizeCorpus.Projectivize(workingDirectory, input, output, "pp-reverse");
                f.deleteOnExit();
                f = new File("pp-reverse.mco");
                f.deleteOnExit();

                f = new File(ppReversedFileName);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("Error: cannot projectivize corpus");
            }
        }

        String reversedFileName = workingDirectory + File.separator + f.getName() + ".reversed";
        SystemLogger.logger().debug("Reversing " + phase_name + " corpus to " + reversedFileName + "\n");
        ReverseCorpus.reverseCorpus(f.getAbsolutePath(), reversedFileName);
        f = new File(reversedFileName);
        f.deleteOnExit();
    }

    if (ltr_pseudo_projective && run.equals(Const.RUN_TRAIN)) {
        File f = new File(file_name);
        File f1 = new File(workingDirectory + File.separator + f.getName());
        f1.deleteOnExit();
        FileUtils.copyFile(f, f1);
        String ppFileName = workingDirectory + File.separator + f.getName() + ".pp";
        try {
            SystemLogger.logger().debug("Projectivise " + phase_name + " corpus to " + ppFileName + "\n");
            String input = f.getName();
            f = new File(ppFileName);
            String output = f.getName();
            ProjectivizeCorpus.Projectivize(workingDirectory, input, output, "pp");
            f.deleteOnExit();
            f = new File("pp.mco");
            f.deleteOnExit();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Error: cannot projectivize corpus");
        }
    }

    if (multiThreaded) {
        ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
        for (Runnable job : jobs) {
            threadPool.execute(job);
        }
        threadPool.shutdown();
        this.waitForThreads(jobs.size());
    } else {
        for (Runnable job : jobs) {
            job.run();
        }
    }

    // run the actual ensemble model
    if (run.equalsIgnoreCase(Const.RUN_TEST)) {
        String outFile = workingDirectory + File.separator + outputPrefix + "." + modelName + "-ensemble";
        List<String> sysFiles = new ArrayList<String>();
        for (String baseModel : baseModels) {
            sysFiles.add(
                    (workingDirectory + File.separator + outputPrefix + "." + modelName + "-" + baseModel));
        }
        // generate the ensemble
        Eisner.ensemble(testCorpus, sysFiles, outFile, reparseAlgorithm);
        // score the ensemble
        Score s = Scorer.evaluate(testCorpus, outFile);
        if (s != null) {
            SystemLogger.logger().info(String.format("ensemble LAS: %.2f %d/%d\n", s.las, s.lcorrect, s.total));
            SystemLogger.logger().info(String.format("ensemble UAS: %.2f %d/%d\n", s.uas, s.ucorrect, s.total));
        }

        SystemLogger.logger().info("Ensemble output saved as: " + outFile + "\n");
    }

    SystemLogger.logger().info("DONE.\n");
}

From source file:BasicEditor3.java

public BasicEditor3() {

    // Action: create new text.
    Action actionNew = new Action("&New", ImageDescriptor.createFromFile(null, "java2s.gif")) {
        public void run() {
            if (handleChangesBeforeDiscard()) {
                file = null;//from w  ww  . j ava2  s  .  co  m
                text.setText("");
            }
        }
    };
    actionNew.setAccelerator(SWT.CTRL + 'N');

    // Action: open a text file.
    Action actionOpen = new Action("&Open", ImageDescriptor.createFromFile(null, "icons/open.gif")) {
        public void run() {
            if (handleChangesBeforeDiscard())
                loadTextFromFile();
        }
    };
    actionOpen.setAccelerator(SWT.CTRL + 'O');

    // Action: save the text to a file. 
    Action actionSave = new Action("&Save\tCtrl+S", ImageDescriptor.createFromFile(null, "icons/save.gif")) {
        public void run() {
            saveTextToFile();
        }
    };
    //actionSave.setAccelerator(SWT.CTRL + 'S');

    // Action: copy selected text.
    Action actionCopy = new Action("&Copy", ImageDescriptor.createFromFile(null, "icons/copy.gif")) {
        public void run() {
            text.copy();
        }
    };
    actionCopy.setAccelerator(SWT.CTRL + 'C');

    // Separator. 

    // Action: cut the selected text. 
    Action actionCut = new Action("Cu&t", ImageDescriptor.createFromFile(null, "icons/cut.gif")) {
        public void run() {
            text.cut();
        }
    };
    actionCut.setAccelerator(SWT.CTRL + 'X');

    // Action: paste the text on clipboard. 
    Action actionPaste = new Action("&Paste", ImageDescriptor.createFromFile(null, "icons/paste.gif")) {
        public void run() {
            text.paste();
        }
    };
    actionPaste.setAccelerator(SWT.CTRL + 'P');

    // Separator. 

    // Action: set wrap property. 
    Action actionWrap = new Action("&Wrap", IAction.AS_CHECK_BOX) {
        public void run() {
            text.setWordWrap(isChecked());
        }
    };
    actionWrap.setAccelerator(SWT.CTRL + 'W');

    // Action: exit. 
    Action actionExit = new Action("&Exit@Ctrl+X") {
        public void run() {
            if (handleChangesBeforeDiscard())
                shell.dispose();
        }
    };

    Action actionPrint = new Action("&Print@Ctrl+P") {
        public void run() {
            printText(text.getText());
        }
    };

    Action actionPrint2 = new Action("Print (StyledText)") {
        public void run() {
            StyledTextPrintOptions options = new StyledTextPrintOptions();
            options.header = "SWT";
            options.footer = "Page <page>";
            options.jobName = "Text";

            Runnable runnable = text.print(new Printer(), options);
            runnable.run();
        }
    };

    // Add a tool bar.
    ToolBar toolBar = new ToolBar(shell, SWT.FLAT | SWT.RIGHT);
    ToolBarManager toolBarManager = new ToolBarManager(toolBar);

    toolBarManager.add(actionNew);
    toolBarManager.add(actionOpen);
    toolBarManager.add(actionSave);
    toolBarManager.add(new Separator());
    toolBarManager.add(actionCopy);
    toolBarManager.add(actionCut);
    toolBarManager.add(actionPaste);

    toolBarManager.add(new Separator());

    toolBarManager.add(actionWrap);

    toolBarManager.add(new Separator());
    toolBarManager.add(actionPrint);
    toolBarManager.add(actionPrint2);

    toolBarManager.update(true);

    shell.setText(APP_NAME);
    shell.setLayout(new GridLayout());

    text = new StyledText(shell, SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
    text.setLayoutData(new GridData(GridData.FILL_BOTH));

    Font font = new Font(shell.getDisplay(), "Courier New", 10, SWT.NORMAL);
    text.setFont(font);

    text.setText("BasicEditor version 3.0\r\nWriten by Jack Li Guojie. ");
    text.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            hasUnsavedChanges = true;
        }
    });

    // Add menus.
    MenuManager barMenuManager = new MenuManager();

    MenuManager fileMenuManager = new MenuManager("&File");
    MenuManager editMenuManager = new MenuManager("&Edit");
    MenuManager formatMenuManager = new MenuManager("&Format");

    barMenuManager.add(fileMenuManager);
    barMenuManager.add(editMenuManager);
    barMenuManager.add(formatMenuManager);

    fileMenuManager.add(actionNew);
    fileMenuManager.add(actionOpen);
    fileMenuManager.add(actionSave);
    fileMenuManager.add(actionPrint);
    fileMenuManager.add(new Separator());

    fileMenuManager.add(actionExit);

    editMenuManager.add(actionCopy);
    editMenuManager.add(actionCut);
    editMenuManager.add(actionPaste);

    formatMenuManager.add(actionWrap);

    // Add the menu bar to the shell.
    // shell.setMenuBar(menuBar);
    barMenuManager.updateAll(true);
    shell.setMenuBar(barMenuManager.createMenuBar((Decorations) shell));

    shell.setSize(400, 200);
    shell.open();

    // Set up the event loop.
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            // If no more entries in event queue
            display.sleep();
        }
    }

    display.dispose();
}

From source file:gov.va.isaac.gui.ConceptNode.java

public void clear() {
    logger.debug("Clear called");
    Runnable r = new Runnable() {
        @Override//  ww  w  .  j  av a2  s  .co m
        public void run() {
            cb_.setValue(new SimpleDisplayConcept("", 0));
        }
    };

    if (Platform.isFxApplicationThread()) {
        r.run();
    } else {
        Platform.runLater(r);
    }
}