Example usage for java.lang Thread start

List of usage examples for java.lang Thread start

Introduction

In this page you can find the example usage for java.lang Thread start.

Prototype

public synchronized void start() 

Source Link

Document

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

Usage

From source file:edu.umass.cs.gnsserver.installer.EC2Runner.java

/**
 * Starts a set of EC2 hosts running GNS that we call a runset.
 *
 * @param runSetName//w  ww  .  jav  a 2  s .c om
 */
public static void createRunSetMulti(String runSetName) {
    int timeout = AWSEC2.DEFAULTREACHABILITYWAITTIME;
    System.out.println("EC2 User Name: " + ec2UserName);
    System.out.println("AMI Name: " + amiRecordType.toString());
    System.out.println("Datastore: " + dataStoreType.toString());
    //preferences.put(RUNSETNAME, runSetName); // store the last one
    startAllMonitoringAndGUIProcesses();
    attachShutDownHook(runSetName);
    ArrayList<Thread> threads = new ArrayList<Thread>();
    // use threads to do a bunch of installs in parallel
    do {
        hostsThatDidNotStart.clear();
        //StatusModel.getInstance().queueDeleteAllEntries(); // for gui
        int cnt = STARTINGNODENUMBER;
        for (EC2RegionSpec regionSpec : regionsList) {
            int i;
            for (i = 0; i < regionSpec.getCount(); i++) {
                threads.add(new EC2RunnerThread(runSetName, regionSpec.getRegion(), Integer.toString(cnt),
                        i == 0 ? regionSpec.getIp() : null, timeout));
                cnt = cnt + 1;
            }
        }
        for (Thread thread : threads) {
            thread.start();
        }
        // and wait for all of them to complete
        try {
            for (Thread thread : threads) {
                thread.join();
            }
        } catch (InterruptedException e) {
            System.out.println("Problem joining threads: " + e);
        }

        if (!hostsThatDidNotStart.isEmpty()) {
            System.out.println("Hosts that did not start: " + hostsThatDidNotStart.keySet());
            timeout = (int) ((float) timeout * 1.5);
            System.out.println("Maybe kill them all and try again with timeout " + timeout + "ms?");
            if (showDialog("Hosts that did not start: " + hostsThatDidNotStart.keySet()
                    + "\nKill them all and try again with with timeout " + timeout + "ms?"
                    + "\nIf you don't respond in 10 seconds this will happen.", 10000)) {
                System.out.println("Yes, kill them all and try again with timeout " + timeout + "ms.");
                terminateRunSet(runSetName);
            } else {
                terminateRunSet(runSetName);
                System.out.println("No, kill them all and quit.");
                return;
            }
        }

        threads.clear();

        // keep repeating until everything starts
    } while (!hostsThatDidNotStart.isEmpty());

    // got a complete set running... now on to step 2
    System.out.println(hostTable.toString());
    // after we know all the hosts are we run the last part

    System.out.println("Hosts that did not start: " + hostsThatDidNotStart.keySet());
    // write out a config file that the GNS installer can use for this set of EC2 hosts
    writeGNSINstallerConf(configName);
    removeShutDownHook();
    System.out.println("Finished creation of Run Set " + runSetName);
}

From source file:gate.Main.java

/** Run the user interface. */
protected static void runGui() throws GateException {

    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

    // initialise the library and load user CREOLE directories
    try {/*  w w w.  j ava  2  s. co  m*/
        Gate.init();
    } catch (Throwable t) {
        log.error("Problem while initialising GATE", t);
        int selection = JOptionPane.showOptionDialog(null,
                "Error during initialisation:\n" + t.toString() + "\nDo you still want to start GATE?", "GATE",
                JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null,
                new String[] { "Cancel", "Start anyway" }, "Cancel");
        if (selection != 1) {
            System.exit(1);
        }
    }

    //create the main frame, show it
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment()
                    .getDefaultScreenDevice().getDefaultConfiguration();

            //this needs to run before any GUI component is constructed.
            applyUserPreferences();

            //all the defaults tables have been updated; build the GUI
            frame = MainFrame.getInstance(gc);
            if (DEBUG)
                Out.prln("constructing GUI");

            // run the GUI
            frame.setTitleChangable(true);
            frame.setTitle(name + " " + version + " build " + build);

            // Set title from Java properties
            String title = System.getProperty(GateConstants.TITLE_JAVA_PROPERTY_NAME);
            if (title != null) {
                frame.setTitle(title);
            } // if
            frame.setTitleChangable(false);

            // Set icon from Java properties
            // iconName could be absolute or "gate:/img/..."
            String iconName = System.getProperty(GateConstants.APP_ICON_JAVA_PROPERTY_NAME);
            if (iconName != null) {
                try {
                    frame.setIconImage(Toolkit.getDefaultToolkit().getImage(new URL(iconName)));
                } catch (MalformedURLException mue) {
                    log.warn("Could not load application icon.", mue);
                }
            } // if

            // Validate frames that have preset sizes
            frame.validate();

            // Center the window
            Rectangle screenBounds = gc.getBounds();
            Dimension screenSize = screenBounds.getSize();
            Dimension frameSize = frame.getSize();
            if (frameSize.height > screenSize.height) {
                frameSize.height = screenSize.height;
            }
            if (frameSize.width > screenSize.width) {
                frameSize.width = screenSize.width;
            }
            frame.setLocation((screenSize.width - frameSize.width) / 2,
                    (screenSize.height - frameSize.height) / 2);

            frame.setVisible(true);

            //load session if required and available;
            //do everything from a new thread.
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        File sessionFile = Gate.getUserSessionFile();
                        if (sessionFile.exists()) {
                            MainFrame.lockGUI("Loading saved session...");
                            PersistenceManager.loadObjectFromFile(sessionFile);
                        }
                    } catch (Exception e) {
                        log.warn("Failed to load session data", e);
                    } finally {
                        MainFrame.unlockGUI();
                    }
                }
            };
            Thread thread = new Thread(Thread.currentThread().getThreadGroup(), runnable, "Session loader");
            thread.setPriority(Thread.MIN_PRIORITY);
            thread.start();
        }
    });
    registerCreoleUrls();
}

From source file:com.dumbster.smtp.SimpleSmtpServer.java

/**
 * Creates an instance of SimpleSmtpServer and starts it.
 * /*ww w.  j  a v a2s  .  c  o m*/
 * @param port
 *            port number the server should listen to
 * @return a reference to the SMTP server
 */
public static SimpleSmtpServer start(int port) {
    logger.info("SMTP Server starting on " + port);
    SimpleSmtpServer server = new SimpleSmtpServer(port);
    Thread t = new Thread(server);

    // Block until the server socket is created
    synchronized (server) {
        try {
            t.start();
            server.wait();
        } catch (InterruptedException e) {
            // Ignore don't care.
        }
    }
    return server;
}

From source file:net.kungfoo.grizzly.proxy.impl.Activator.java

private static void startReactor() {
    Thread t = new Thread(new Runnable() {
        @SuppressWarnings({ "UseOfSystemOutOrSystemErr" })
        public void run() {
            try {
                connectingIOReactor.execute(connectingEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
                e.printStackTrace(System.err);
            }//from w  w w .j  a  v a2 s . co m
        }
    });
    t.start();
}

From source file:com.meltmedia.dropwizard.etcd.json.EtcdWatchServiceIT.java

public static Thread startWaitThread(long timeout, TimeUnit unit) {
    Thread waitThread = new Thread(() -> {
        try {/*from  w  w w .j a va 2s .c  o  m*/
            unit.sleep(timeout);
        } catch (Exception e) {
            // oh well!
        }
    });
    waitThread.start();
    return waitThread;
}

From source file:agileinterop.AgileInterop.java

private static JSONObject getPSRData(String body) throws ParseException, InterruptedException, APIException {
    // Parse body as JSON
    JSONParser parser = new JSONParser();
    JSONArray jsonBody = (JSONArray) parser.parse(body);

    Map<String, Object> data = new HashMap<>();

    class GetObjectData implements Runnable {
        private String psrNumber;
        private Map<String, Object> data;
        private IServiceRequest psr;

        public GetObjectData(String psrNumber, Map<String, Object> data)
                throws APIException, InterruptedException {
            this.psrNumber = psrNumber;
            this.data = data;

            psr = (IServiceRequest) Agile.session.getObject(IServiceRequest.OBJECT_TYPE, psrNumber);
        }/*www  .  ja va  2  s  .c  o m*/

        @Override
        public void run() {
            this.data.put(psrNumber, new HashMap<String, Object>());

            try {
                if (psr != null) {
                    getCellValues();
                    getAttachments();
                    getHistory();
                }
            } catch (APIException ex) {
                Logger.getLogger(AgileInterop.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        private void getCellValues() throws APIException {
            Map<String, Object> cellValues = new HashMap<>();

            long startTime = System.currentTimeMillis();

            // Get cell values
            ICell[] cells = psr.getCells();
            for (ICell cell : cells) {
                if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                    if (cell.getValue() != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                        sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                        cellValues.put(cell.getName(), sdf.format((Date) cell.getValue()));
                    } else {
                        cellValues.put(cell.getName(), cell.toString());
                    }
                } else {
                    cellValues.put(cell.getName(), cell.toString());
                }
            }

            long endTime = System.currentTimeMillis();

            String logMessage = String.format("%s: getCellValues executed in %d milliseconds", psrNumber,
                    endTime - startTime);
            System.out.println(logMessage);

            ((HashMap<String, Object>) this.data.get(psrNumber)).put("cellValues", cellValues);
        }

        private void getAttachments() throws APIException {
            List<Map<String, String>> attachments = new ArrayList<>();

            long startTime = System.currentTimeMillis();

            // Get attachments information
            ITable table = psr.getTable("Attachments");
            ITwoWayIterator tableIterator = table.getTableIterator();
            while (tableIterator.hasNext()) {
                IRow row = (IRow) tableIterator.next();
                Map<String, String> attachment = new HashMap<>();

                ICell[] cells = row.getCells();
                for (ICell cell : cells) {
                    if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                        if (cell.getValue() != null) {
                            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                            sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                            attachment.put(cell.getName(), sdf.format((Date) cell.getValue()));
                        } else {
                            attachment.put(cell.getName(), cell.toString());
                        }
                    } else {
                        attachment.put(cell.getName(), cell.toString());
                    }
                }

                attachments.add(attachment);
            }

            long endTime = System.currentTimeMillis();

            String logMessage = String.format("%s: getAttachments executed in %d milliseconds", psrNumber,
                    endTime - startTime);
            System.out.println(logMessage);

            ((HashMap<String, Object>) this.data.get(psrNumber)).put("attachments", attachments);
        }

        private void getHistory() throws APIException {
            List<Map<String, String>> histories = new ArrayList<>();

            long startTime = System.currentTimeMillis();

            // Get history information
            ITable table = psr.getTable("History");
            ITwoWayIterator tableIterator = table.getTableIterator();
            while (tableIterator.hasNext()) {
                IRow row = (IRow) tableIterator.next();
                Map<String, String> history = new HashMap<>();

                ICell[] cells = row.getCells();
                for (ICell cell : cells) {
                    if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                        if (cell.getValue() != null) {
                            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                            sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                            history.put(cell.getName(), sdf.format((Date) cell.getValue()));
                        } else {
                            history.put(cell.getName(), cell.toString());
                        }
                    } else {
                        history.put(cell.getName(), cell.toString());
                    }
                }

                histories.add(history);
            }

            long endTime = System.currentTimeMillis();

            String logMessage = String.format("%s: getHistory executed in %d milliseconds", psrNumber,
                    endTime - startTime);
            System.out.println(logMessage);

            ((HashMap<String, Object>) this.data.get(psrNumber)).put("history", histories);
        }
    }

    synchronized (data) {
        // Do something funky with the first one
        Thread t = new Thread(new GetObjectData(jsonBody.get(0).toString(), data));
        t.start();
        t.join();

        ExecutorService executor = Executors.newFixedThreadPool(10);
        for (Object object : jsonBody.subList(1, jsonBody.size() - 1)) {
            executor.execute(new Thread(new GetObjectData(object.toString(), data)));
        }

        executor.shutdown();
        while (!executor.isTerminated()) {
        }
    }

    JSONObject obj = new JSONObject();
    obj.put("data", data);
    return obj;
}

From source file:com.meltmedia.dropwizard.etcd.json.EtcdWatchServiceIT.java

public static Thread startNodeDataThread(EtcdDirectoryDao<NodeData> dao, int count) {
    Thread events = new Thread(() -> {
        for (int i = 0; i < count; i++) {
            dao.put(String.valueOf(i), new NodeData().withName(String.valueOf(i)));
        }//from   w ww .  j  a  v  a2 s .  c  om
    });
    events.start();
    return events;
}

From source file:SerialIntList.java

/**
 * Use object serialization to make a "deep clone" of the object o. This
 * method serializes o and all objects it refers to, and then deserializes
 * that graph of objects, which means that everything is copied. This differs
 * from the clone() method of an object which is usually implemented to
 * produce a "shallow" clone that copies references to other objects, instead
 * of copying all referenced objects./*from   w  w  w . ja v a  2s .  c om*/
 */
static Object deepclone(final Serializable o) throws IOException, ClassNotFoundException {
    // Create a connected pair of "piped" streams.
    // We'll write bytes to one, and them from the other one.
    final PipedOutputStream pipeout = new PipedOutputStream();
    PipedInputStream pipein = new PipedInputStream(pipeout);

    // Now define an independent thread to serialize the object and write
    // its bytes to the PipedOutputStream
    Thread writer = new Thread() {
        public void run() {
            ObjectOutputStream out = null;
            try {
                out = new ObjectOutputStream(pipeout);
                out.writeObject(o);
            } catch (IOException e) {
            } finally {
                try {
                    out.close();
                } catch (Exception e) {
                }
            }
        }
    };
    writer.start(); // Make the thread start serializing and writing

    // Meanwhile, in this thread, read and deserialize from the piped
    // input stream. The resulting object is a deep clone of the original.
    ObjectInputStream in = new ObjectInputStream(pipein);
    return in.readObject();
}

From source file:net.sf.sahi.util.Utils.java

public static String executeCommand(final String command, boolean isSync, long timeout) throws Exception {
    final RunnableWithResult runnable = new RunnableWithResult(command);
    final Thread thread = new Thread(runnable);
    thread.start();
    if (isSync)/*from  w ww.j ava2  s.c o m*/
        thread.join(timeout);
    return runnable.getResult();
}

From source file:com.emental.mindraider.core.search.SearchCommander.java

/**
 * Rebuild search index./*from ww  w  .jav a  2s. c  o  m*/
 */
public static void rebuildSearchAndTagIndices() {
    logger.debug(Messages.getString("SearchCommander.reindexing", MindRaider.profile.getNotebooksDirectory()));

    Thread thread = new Thread() {
        public void run() {
            try {
                SearchCommander.rebuild(MindRaider.profile.getNotebooksDirectory());
            } catch (IOException e) {
                logger.error(Messages.getString("SearchCommand.unableToRebuildSearchIndex"), e);
            }
        }
    };
    thread.setDaemon(true);
    thread.start();
}