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:net.geoprism.gis.geoserver.GeoserverInitializer.java

public static void setup() {
    GeoserverInitializer init = new GeoserverInitializer();

    try {// w ww  .j a  v  a2  s . c  om
        initLog.debug("Attempting to initialize context.");

        // create another thread to avoid blocking the one starting the webapps.
        Thread t = new Thread(new CheckThread());
        t.setUncaughtExceptionHandler(init);
        t.setDaemon(true);
        t.start();

        initLog.debug("Context initialized...[" + GeoserverInitializer.class + "] started.");
    } catch (Throwable t) {
        initLog.error("Could not initialize context.", t);
    }

    // Start the mapping database view cleanup thread
    Thread t = new Thread(cleanup);
    t.setUncaughtExceptionHandler(init);
    t.setDaemon(true);
    t.start();

    // scheduler.scheduleWithFixedDelay(new CleanupRunnable(), 1, 5, TimeUnit.MINUTES);
}

From source file:com.cueup.hegemon.TestUtils.java

public static void runConcurrent(int count, Runnable r) throws InterruptedException {
    List<Thread> threads = Lists.newArrayList();
    ErrorCollector errorCollector = new ErrorCollector();

    for (int i = 0; i < count; i++) {
        Thread t = new Thread(r);
        t.setName("testThread" + i);
        t.setUncaughtExceptionHandler(errorCollector);
        threads.add(t);/*from   w ww.  j  a  v  a 2  s. com*/

    }

    for (Thread t : threads) {
        t.start();
    }

    for (Thread t : threads) {
        t.join();
    }

    errorCollector.assertNoErrors();
}

From source file:Main.java

/**
 * Utility method that sets name, daemon status and starts passed thread.
 * @param t thread to frob/*from   ww  w .j  a  v  a  2  s. co m*/
 * @param name new name
 * @param handler A handler to set on the thread.  Pass null if want to
 * use default handler.
 * @return Returns the passed Thread <code>t</code>.
 */
public static Thread setDaemonThreadRunning(final Thread t, final String name,
        final UncaughtExceptionHandler handler) {
    t.setName(name);
    if (handler != null) {
        t.setUncaughtExceptionHandler(handler);
    }
    t.setDaemon(true);
    t.start();
    return t;
}

From source file:com.strategicgains.docussandra.controller.perf.remote.mongo.MongoLoader.java

public static void loadMongoData(MongoClientURI uri, final int NUM_WORKERS, Database database,
        final int numDocs, final PerfTestParent clazz) {
    logger.info("------------Loading Data into: " + database.name() + " with MONGO!------------");
    try {//from  w  w  w.j a  v  a 2 s.c o m
        try {
            MongoClient mongoClient = new MongoClient(uri);
            mongoClient.setWriteConcern(WriteConcern.MAJORITY);
            DB db = mongoClient.getDB(database.name());
            final DBCollection coll = db.getCollection(database.name());
            ArrayList<Thread> workers = new ArrayList<>(NUM_WORKERS + 1);
            int docsPerWorker = numDocs / NUM_WORKERS;
            try {
                List<Document> docs = clazz.getDocumentsFromFS();
                ArrayList<List<Document>> documentQueues = new ArrayList<>(NUM_WORKERS + 1);
                int numDocsAssigned = 0;
                while ((numDocsAssigned + 1) < numDocs) {
                    int start = numDocsAssigned;
                    int end = numDocsAssigned + docsPerWorker;
                    if (end > numDocs) {
                        end = numDocs - 1;
                    }
                    documentQueues.add(new ArrayList(docs.subList(start, end)));
                    numDocsAssigned = end;
                }
                for (final List<Document> queue : documentQueues) {
                    workers.add(new Thread() {
                        @Override
                        public void run() {
                            for (Document d : queue) {
                                DBObject o = (DBObject) JSON.parse(d.object());
                                coll.save(o);
                            }
                            logger.info("Thread " + Thread.currentThread().getName() + " is done. It processed "
                                    + queue.size() + " documents.");
                        }
                    });
                }
            } catch (UnsupportedOperationException e)//we can't read everything in at once
            {
                //all we need to do in this block is find a way to set "workers"
                for (int i = 0; i < NUM_WORKERS; i++) {
                    workers.add(new Thread() {
                        private final int chunk = (int) (Math.random() * 100) + 150;//pick a random chunk so we are not going back to the FS all at the same time and potentially causing a bottle neck

                        @Override
                        public void run() {
                            ThreadLocal<Integer> counter = new ThreadLocal<>();
                            counter.set(new Integer(0));
                            try {
                                List<Document> docs = clazz.getDocumentsFromFS(chunk);//grab a handful of documents
                                while (docs.size() > 0) {
                                    for (Document d : docs)//process the documents we grabbed
                                    {
                                        DBObject o = (DBObject) JSON.parse(d.object());
                                        coll.save(o);
                                        counter.set(counter.get() + 1);
                                    }
                                    docs = clazz.getDocumentsFromFS(chunk);//grab another handful of documents
                                }
                                logger.info("Thread " + Thread.currentThread().getName()
                                        + " is done. It processed " + counter.get() + " documents.");
                            } catch (IOException | ParseException e) {
                                logger.error("Couldn't read from document", e);
                            }
                        }
                    });
                }
            }

            long start = new Date().getTime();
            //start your threads!
            for (Thread t : workers) {
                t.start();
            }
            logger.info("All threads started, waiting for completion.");
            boolean allDone = false;
            boolean first = true;
            while (!allDone || first) {
                first = false;
                boolean done = true;
                for (Thread t : workers) {
                    if (t.isAlive()) {
                        done = false;
                        logger.info("Thread " + t.getName() + " is still running.");
                        break;
                    }
                }
                if (done) {
                    allDone = true;
                } else {
                    logger.info("We still have workers running...");
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                    }
                }
            }
            long end = new Date().getTime();
            long miliseconds = end - start;
            double seconds = (double) miliseconds / 1000d;
            output.info("Done loading data using: " + NUM_WORKERS + ". Took: " + seconds + " seconds");
            double tpms = (double) numDocs / (double) miliseconds;
            double tps = tpms * 1000;
            double transactionTime = (double) miliseconds / (double) numDocs;
            output.info(database.name() + " Mongo Average Transactions Per Second: " + tps);
            output.info(
                    database.name() + " Mongo Average Transactions Time (in miliseconds): " + transactionTime);

        } catch (UnknownHostException e) {
            logger.error("Couldn't connect to Mongo Server", e);
        }
    } catch (IOException | ParseException e) {
        logger.error("Couldn't read data.", e);
    }
}

From source file:com.flexive.testRunner.FxTestRunner.java

/**
 * Runs tests - this is a "fire and forget" function, callers have to make sure to not call this more than once!
 *
 * @param callback   the callback for results
 * @param outputPath test report output path
 *///ww  w .  j a v a 2 s  .com
public static void runTests(FxTestRunnerCallback callback, String outputPath) {
    if (FxTestRunnerThread.isTestInProgress()) {
        LOG.error("A test is currently running. Tried to start another run!");
        return;
    }
    Thread t = new FxTestRunnerThread(callback, outputPath);
    t.setDaemon(true);
    if (callback != null)
        callback.setRunning(true);
    t.start();
}

From source file:com.modeln.build.common.tool.CMnCmdLineTool.java

/**
 * Prompt for user input "yes/no" to continue with the program or not.
 * The user will continue to be prompted for unput until either yes 
 * or no is provided.//w  ww.  j  a  v  a 2 s. c om
 *
 * @param   question   The question to present to the user
 * @return true if user answers yes, false otherwise
 */
public static boolean doContinue(String question) {
    String yes = "yes";
    String no = "no";

    String prompt = question + " (" + yes + "/" + no + "): ";
    String answer = null;
    boolean validResponse = false;
    boolean saidYes = false;

    try {
        // Prompt the user for input
        CMnContinuousPrompt cp = new CMnContinuousPrompt(promptInterval, prompt);
        Thread t = new Thread(cp);
        t.start();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while (!validResponse) {
            cp.showPrompt();
            answer = br.readLine().trim();
            validResponse = (answer.equalsIgnoreCase(yes) || answer.equalsIgnoreCase(no));
        }
        cp.setEnabled(false);

        // Determine whether the user responded "yes"
        saidYes = answer.equalsIgnoreCase(yes);

    } catch (IOException e) {
        e.printStackTrace();
    }

    return saidYes;
}

From source file:smn.learn.jcassandra.TsubscribeServer.java

public static void serve(String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("Please specify document root directory");
        System.exit(1);// w w  w  . j  a v a  2s  . co  m
    }
    Thread t = new RequestListenerThread(8080, args[0]);
    t.setDaemon(false);
    t.start();
}

From source file:com.manning.androidhacks.hack023.net.NetworkUtilities.java

public static Thread performOnBackgroundThread(final Runnable runnable) {
    final Thread t = new Thread() {
        @Override//from  w ww . j  ava  2 s  . c o m
        public void run() {
            try {
                runnable.run();
            } finally {

            }
        }
    };
    t.start();
    return t;
}

From source file:mase.MaseEvolve.java

public static Thread launchExperiment(File config) throws IOException {
    // Call ec.Evolve
    final String[] args = new String[] { Evolve.A_FILE, config.getAbsolutePath() };
    Thread t = new Thread(new Runnable() {
        @Override//from ww w.j  a va  2s.c  o  m
        public void run() {
            ec.Evolve.main(args);
        }
    });
    t.start();
    return t;
}

From source file:com.bjorsond.android.timeline.sync.ServerUploader.java

/**
 * Sends a JSON-string to the Google App Engine Server. This runs async in a separate thread.
 * //from   w w w.  j  a v a  2  s  . c o  m
 * @param jsonString Content of HTTP request, as JSON.
 * @param targetHost The host of the server
 * @param httpPut The HTTP PUT request.
 */
private static void sendJSONTOGAEServer(final String jsonString, final HttpHost targetHost,
        final HttpPut httpPut) {
    Runnable sendRunnable = new Runnable() {

        public void run() {
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();

                StringEntity entity = new StringEntity(jsonString, "UTF-8");
                httpPut.setEntity(entity);

                // execute is a blocking call, it's best to call this code in a thread separate from the ui's
                HttpResponse response = httpClient.execute(targetHost, httpPut);

                Log.v("Put to GAE", response.getStatusLine().toString());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };

    Thread thread = new Thread(null, sendRunnable, "putToGAE");
    thread.start();

}