Example usage for java.lang Thread Thread

List of usage examples for java.lang Thread Thread

Introduction

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

Prototype

public Thread(Runnable target, String name) 

Source Link

Document

Allocates a new Thread object.

Usage

From source file:com.jgoetsch.eventtrader.EventTraderSpringLauncher.java

public static void main(String[] args) {
    if (args.length < 1) {
        System.out.println("Usage: " + EventTraderSpringLauncher.class.getSimpleName() + " <files>...");
        System.out.println("       files - List of paths to spring bean definition xml files.");
        System.out.println("               Each object defined that implements Runnable will be executed");
        System.out.println("               in its own thread.");
    } else {//from  w  w w  .j a  va2  s  .  c  om
        AbstractApplicationContext context = new ClassPathXmlApplicationContext(args);

        // auto register growl notifications after all GrowlNotification objects have been instantiated
        // if it is found on the classpath
        try {
            Class.forName("com.jgoetsch.eventtrader.processor.GrowlNotification").getMethod("autoRegister")
                    .invoke(null);
        } catch (Exception e) {
            log.warn("Growl not found, cannot autoRegister notifications: {}", e.getMessage());
        }

        Map<String, Runnable> runnables = BeanFactoryUtils.beansOfTypeIncludingAncestors(context,
                Runnable.class);
        List<Thread> threads = new ArrayList<Thread>(runnables.size());
        for (final Map.Entry<String, Runnable> runner : runnables.entrySet()) {
            final Thread th = new Thread(runner.getValue(), runner.getKey());
            threads.add(th);
            th.start();
        }

        // close spring context on JVM shutdown
        // this causes all @PreDestroy methods in the runnables to be called to allow for
        // them to shutdown gracefully
        context.registerShutdownHook();

        // wait for launched threads to finish before cleaning up beans
        for (Thread th : threads) {
            try {
                th.join();
            } catch (InterruptedException e) {
            }
        }
    }
}

From source file:com.sm.store.TestMultiClient.java

public static void main(String[] args) throws Exception {
    String[] opts = new String[] { "-thread", "-times", "-host", "-port", "-store" };
    String[] defaults = new String[] { "2", "10", "localhost", "7100", "keystore" };
    String[] paras = getOpts(args, opts, defaults);
    int threads = Integer.valueOf(paras[0]);
    int times = Integer.valueOf(paras[1]);
    String host = paras[2];//from  ww w.  j  a  v a2 s . c  o  m
    int port = Integer.valueOf(paras[3]);
    String store = paras[4];

    for (int i = 0; i < threads; i++) {
        com.sm.store.client.RemoteClientImpl client = new GZRemoteClientImpl(host + ":" + port, null, store);
        logger.info("start thread  =>" + i);
        new Thread(new RunnerThread(client, times, i), "thread-" + i).start();
    }
}

From source file:com.sm.store.TestClient.java

public static void main(String[] args) throws Exception {
    String[] opts = new String[] { "-thread", "-times", "-host", "-port" };
    String[] defaults = new String[] { "2", "10", "localhost", "7100" };
    String[] paras = getOpts(args, opts, defaults);
    int threads = Integer.valueOf(paras[0]);
    int times = Integer.valueOf(paras[1]);
    String host = paras[2];/*w w w.  j a va  2s. c  o m*/
    int port = Integer.valueOf(paras[3]);

    for (int i = 0; i < threads; i++) {
        TCPClient client = createClient(host, port);
        logger.info("start thread  =>" + i);
        new Thread(new RunnerThread(client, times, i), "thread-" + i).start();
    }
}

From source file:com.yahoo.ads.pb.mttf.PistachiosBenchmarking.java

public static void main(String[] args) {
    int threadCount = 50;
    logger.info("parsing error {}", args.length);
    if (args.length >= 1) {
        try {// w ww. ja v a2s  .  c o  m
            threadCount = Integer.parseInt(args[0]);
            logger.info("parsd {} {}", args[0], threadCount);
        } catch (Exception e) {
            logger.info("parsing error", e);
        }
    }
    if (args.length >= 2) {
        try {
            recordAverageSize = Integer.parseInt(args[1]);
            logger.info("parsd {} {}", args[1], recordAverageSize);
        } catch (Exception e) {
            logger.info("parsing error", e);
        }
    }

    for (int i = 0; i < threadCount; i++) {
        Thread thread = new Thread(new PistachiosBenchmarking(), "benchmarking" + i);
        thread.start();
    }

}

From source file:integration.HeavyLoad.java

public static void main(String[] args) throws IOException {
    url = args[0] + "/create.json";
    final String specFile = args[1];

    for (int i = 2; i < args.length; i++) {
        String server = args[i];/*from   w  w w. j  av  a 2s . co  m*/
        servers.add(new ServerStats(server));
    }
    if (servers.isEmpty()) {
        servers.add(new ServerStats(DEFAULT));
    }

    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    final HttpConnectionManagerParams params = connectionManager.getParams();
    params.setSoTimeout(TIMEOUT);
    params.setConnectionTimeout(TIMEOUT);
    params.setDefaultMaxConnectionsPerHost(NB_THREADS);
    params.setMaxTotalConnections(NB_THREADS);

    httpClient = new HttpClient(connectionManager);

    spec = FileUtilities.readWholeTextFile(new File(specFile));

    Thread[] threads = new Thread[NB_THREADS];
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread(new Reader(), "reader-" + i);
        threads[i].start();
    }
    for (int i = 0; i < threads.length; i++) {
        try {
            threads[i].join();
        } catch (InterruptedException e) {
        }
    }
}

From source file:PriorityCompete.java

public static void main(String[] args) {
    Runnable r = new Runnable() {
        public void run() {
            System.out.println("Run without using yield()");
            System.out.println("=========================");
            runSet(false);//  w  w w  . ja  va 2 s  . c  o m

            System.out.println();
            System.out.println("Run using yield()");
            System.out.println("=================");
            runSet(true);
        }
    };

    Thread t = new Thread(r, "Priority");
    t.setPriority(Thread.MAX_PRIORITY - 1);
    t.start();
}

From source file:com.ciphertool.zodiacengine.CipherSolutionEngine.java

/**
 * @param args//from w w w .  j  ava  2s.  c o  m
 * @throws InterruptedException
 */
public static void main(String[] args) throws InterruptedException {
    // Spin up the Spring application context
    setUp();

    CipherDto cipherDto = null;
    Runnable cipherTask = null;
    Thread cipherWorker = null;
    long threadIterations = 0;
    Cipher cipher = cipherDao.findByCipherName(cipherName);

    long start = System.currentTimeMillis();

    List<Thread> threads = new ArrayList<Thread>();
    List<CipherDto> cipherDtos = new ArrayList<CipherDto>();

    if (maxThreads > numIterations) {
        log.warn("The number of threads is greater than the number of tasks.  Reducing thread count to "
                + numIterations + ".");

        maxThreads = (int) numIterations;
    }

    log.info("Beginning solution generation.  Generating " + numIterations + " solutions using " + maxThreads
            + " threads.");

    for (int i = 1; i <= maxThreads; i++) {
        threadIterations = (numIterations / maxThreads);
        if (i == 1) {
            /*
             * If the number of iterations doesn't divide evenly among the
             * threads, add the remainder to the first thread
             */
            threadIterations += (numIterations % maxThreads);
        }

        cipherDto = new CipherDto(String.valueOf(i), cipher);
        cipherDtos.add(cipherDto);

        cipherTask = new CipherSolutionRunnable(threadIterations, solutionGenerator, solutionEvaluator,
                cipherDto);

        cipherWorker = new Thread(cipherTask, String.valueOf(i));

        cipherWorker.start();
        threads.add(cipherWorker);
    }

    /*
     * Keep checking threads until no more are left running
     */
    int running = 0;
    do {
        running = 0;
        for (Thread thread : threads) {
            if (thread.isAlive()) {
                running++;
            }
        }

        /*
         * There's no need to loop through this as fast as possible. Sleep
         * for a short period so that there isn't so much overhead from
         * monitoring the threads' state.
         */
        Thread.sleep(monitorSleepMillis);
    } while (running > 0);

    long totalSolutions = 0;
    long totalMatchSum = 0;
    long uniqueMatchSum = 0;
    long adjacentMatchSum = 0;

    BigInteger cipherId = cipher.getId();
    int rows = cipher.getRows();
    int columns = cipher.getColumns();
    SolutionChromosome solutionMostMatches = new SolutionChromosome(cipherId, 0, 0, 0, rows, columns);
    SolutionChromosome solutionMostUnique = new SolutionChromosome(cipherId, 0, 0, 0, rows, columns);
    SolutionChromosome solutionMostAdjacent = new SolutionChromosome(cipherId, 0, 0, 0, rows, columns);

    /*
     * Sum up all data from all CipherDtos passed to the threads
     */
    for (CipherDto nextCipherDto : cipherDtos) {
        log.debug("Best solution from thread " + nextCipherDto.getThreadName() + ": "
                + nextCipherDto.getSolutionMostMatches());
        log.debug("Most unique solution from thread " + nextCipherDto.getThreadName() + ": "
                + nextCipherDto.getSolutionMostUnique());
        log.debug("Solution with most adjacent matches from thread " + nextCipherDto.getThreadName() + ": "
                + nextCipherDto.getSolutionMostAdjacent());

        totalSolutions += nextCipherDto.getNumSolutions();
        totalMatchSum += nextCipherDto.getTotalMatchSum();
        uniqueMatchSum += nextCipherDto.getUniqueMatchSum();
        adjacentMatchSum += nextCipherDto.getAdjacentMatchSum();

        /*
         * Find the Solution with the highest number of total matches
         */
        if (nextCipherDto.getSolutionMostMatches().getTotalMatches() > solutionMostMatches.getTotalMatches()) {
            solutionMostMatches = nextCipherDto.getSolutionMostMatches();
        }

        /*
         * Find the Solution with the highest number of unique matches in
         * plaintext
         */
        if (nextCipherDto.getSolutionMostUnique().getUniqueMatches() > solutionMostUnique.getUniqueMatches()) {
            solutionMostUnique = nextCipherDto.getSolutionMostUnique();
        }

        /*
         * Find the Solution with the highest number of adjacent matches in
         * plaintext
         */
        if (nextCipherDto.getSolutionMostAdjacent().getAdjacentMatchCount() > solutionMostAdjacent
                .getAdjacentMatchCount()) {
            solutionMostAdjacent = nextCipherDto.getSolutionMostAdjacent();
        }
    }

    /*
     * Print out summary information
     */
    log.info("Took " + (System.currentTimeMillis() - start) + "ms to generate and validate " + totalSolutions
            + " solutions.");
    log.info("Most total matches achieved: " + solutionMostMatches.getTotalMatches());
    log.info("Average total matches: " + (totalMatchSum / totalSolutions));
    log.info("Best solution found: " + solutionMostMatches);
    log.info("Most unique matches achieved: " + solutionMostUnique.getUniqueMatches());
    log.info("Average unique matches: " + (uniqueMatchSum / totalSolutions));
    log.info("Solution with most unique matches found: " + solutionMostUnique);
    log.info("Most adjacent matches achieved: " + solutionMostAdjacent.getAdjacentMatchCount());
    log.info("Average adjacent matches: " + (adjacentMatchSum / totalSolutions));
    log.info("Solution with most adjacent matches found: " + solutionMostAdjacent);
}

From source file:Retailer.java

public static void main(String[] args) {
    String url = "tcp://localhost:61616";
    String user = null;//from  ww  w  .jav  a 2 s .c o m
    String password = null;

    if (args.length >= 1) {
        url = args[0];
    }

    if (args.length >= 2) {
        user = args[1];
    }

    if (args.length >= 3) {
        password = args[2];
    }

    Retailer r = new Retailer(url, user, password);

    new Thread(r, "Retailer").start();
}

From source file:com.nohowdezign.gcpmanager.Main.java

public final static void main(String[] args) {
    //Remove old log, it does not need to be there anymore.
    File oldLog = new File("./CloudPrintManager.log");

    if (oldLog.exists()) {
        oldLog.delete();/*from w  ww .  ja  va  2  s .  com*/
    }

    //Create a file reader for the props file
    Reader propsStream = null;
    try {
        propsStream = new FileReader("./props.json");
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }

    PrintManagerProperties props = null;
    if (propsStream != null) {
        props = gson.fromJson(propsStream, PrintManagerProperties.class);
    } else {
        logger.error("Property file does not exist. Please create one.");
    }

    //Set the variables to what is in the props file
    String email = props.getEmail();
    String password = props.getPassword();
    String printerId = props.getPrinterId();
    amountOfPagesPerPrintJob = props.getAmountOfPagesPerPrintJob();
    timeRestraintsForPrinter = props.getTimeRestraintsForPrinter();

    JobStorageManager.timeToKeepFileInDays = props.getTimeToKeepFileInDays();

    //AuthenticationManager authenticationManager = new AuthenticationManager();
    //authenticationManager.setPasswordToUse(props.getAdministrativePassword());
    //authenticationManager.initialize(1337); //Start the authentication manager on port 1337

    try {
        cloudPrint.connect(email, password, "cloudprintmanager-1.0");
    } catch (CloudPrintAuthenticationException e) {
        logger.error(e.getMessage());
    }

    //TODO: Get a working website ready
    //Thread adminConsole = new Thread(new HttpServer(80), "HttpServer");
    //adminConsole.start();

    Thread printJobManager = new Thread(new JobStorageManagerThread(), "JobStorageManager");
    printJobManager.start();

    try {
        if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
            logger.error("Your operating system is not supported. Please switch to linux ya noob.");
            System.exit(1);
        } else {
            PrinterManager printerManager = new PrinterManager(cloudPrint);

            File cupsPrinterDir = new File("/etc/cups/ppd");

            if (cupsPrinterDir.isDirectory() && cupsPrinterDir.canRead()) {
                for (File cupsPrinterPPD : cupsPrinterDir.listFiles()) {
                    //Init all of the CUPS printers in the manager
                    printerManager.initializePrinter(cupsPrinterPPD, cupsPrinterPPD.getName());
                }
            } else {
                logger.error("Please run this with a higher access level.");
                System.exit(1);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    while (true) {
        try {
            getPrintingJobs(printerId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:ai.grakn.engine.GraknEngineServer.java

public static void main(String[] args) {
    GraknEngineConfig prop = GraknEngineConfig.create();
    // Start Engine
    GraknEngineServer server = start(prop);

    // close GraknEngineServer on SIGTERM
    Thread closeThread = new Thread(server::close, "GraknEngineServer-shutdown");
    Runtime.getRuntime().addShutdownHook(closeThread);
}