List of usage examples for java.lang Thread join
public final void join() throws InterruptedException
From source file:ThreadDemo.java
public static void main(String args[]) { Thread t = new Thread(new ThreadDemo()); System.out.println("Executing " + t.getName()); // this will call run() fucntion t.start();/*from ww w.j a va 2s . c o m*/ // interrupt the threads if (!t.interrupted()) { t.interrupt(); } // block until other threads finish try { t.join(); } catch (InterruptedException e) { } }
From source file:mosaicsimulation.MosaicLockstepServer.java
public static void main(String[] args) { Options opts = new Options(); opts.addOption("s", "serverPort", true, "Listening TCP port used to initiate handshakes"); opts.addOption("n", "nClients", true, "Number of clients that will participate in the session"); opts.addOption("t", "tickrate", true, "Number of transmission session to execute per second"); opts.addOption("m", "maxUDPPayloadLength", true, "Max number of bytes per UDP packet"); opts.addOption("c", "connectionTimeout", true, "Timeout for UDP connections"); DefaultParser parser = new DefaultParser(); CommandLine commandLine = null;/* w ww . jav a2s . co m*/ try { commandLine = parser.parse(opts, args); } catch (ParseException ex) { ex.printStackTrace(); System.exit(1); } int serverPort = Integer.parseInt(commandLine.getOptionValue("serverPort")); int nClients = Integer.parseInt(commandLine.getOptionValue("nClients")); int tickrate = Integer.parseInt(commandLine.getOptionValue("tickrate")); int maxUDPPayloadLength = Integer.parseInt(commandLine.getOptionValue("maxUDPPayloadLength")); int connectionTimeout = Integer.parseInt(commandLine.getOptionValue("connectionTimeout")); Thread serverThread = LockstepServer.builder().clientsNumber(nClients).tcpPort(serverPort) .tickrate(tickrate).maxUDPPayloadLength(maxUDPPayloadLength).connectionTimeout(connectionTimeout) .build(); serverThread.setName("Main-server-thread"); serverThread.start(); try { serverThread.join(); } catch (InterruptedException ex) { LOG.error("Server interrupted while joining"); } }
From source file:de.saly.elasticsearch.importer.imap.IMAPImporterCl.java
public static void main(String[] args) throws Exception { if (args.length < 1) { System.out.println("Usage: IMAPImporterC [-e] <config-file>"); System.exit(-1);/* w w w . j a va2 s. c o m*/ } String configFile = null; boolean embedded = false; if (args.length == 1) { configFile = args[0]; } if (args.length == 2) { embedded = "-e".equals(args[0]); configFile = args[1]; } System.out.println("Config File: " + configFile); System.out.println("Embedded: " + embedded); final Thread mainThread = Thread.currentThread(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("Will shutdown ..."); IMAPImporterCl.stop(); try { mainThread.join(); System.out.println("Shudown done"); } catch (InterruptedException e) { } } }); start(configFile, embedded); }
From source file:com.github.lburgazzoli.sandbox.reactor.ProcessorMain.java
public static void main(String[] args) { try {//from w w w .j a v a 2 s. c om final Processor<Message> processor = new ProcessorSpec<Message>().dataSupplier(new MessageSupplier()) .consume(new ThrottlingMessageConsumer(10)).singleThreadedProducer().dataBufferSize(1024).get(); Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS); Thread th = new Thread(new Runnable() { public void run() { for (int i = 0; i < 20; i++) { Operation<Message> op = processor.get(); op.get().type = i; op.commit(); } } }); th.start(); th.join(); processor.shutdown(); Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS); } catch (Exception e) { LOGGER.warn("Main Exception", e); } }
From source file:httpscheduler.HttpScheduler.java
/** * @param args the command line arguments * @throws java.lang.Exception/*from w w w . j ava2 s. co m*/ */ public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println("Invalid command line parameters for worker"); System.exit(-1); } int fixedExecutorSize = 4; //Creating fixed size executor ThreadPoolExecutor taskCommExecutor = new ThreadPoolExecutor(fixedExecutorSize, fixedExecutorSize, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); // Used for late binding JobMap jobMap = new JobMap(); // Set port number int port = Integer.parseInt(args[0]); // Set worker mode String mode = args[1].substring(2); // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build(); // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); // Different handlers for late binding and generic cases if (mode.equals("late")) reqistry.register("*", new LateBindingRequestHandler(taskCommExecutor, jobMap)); else reqistry.register("*", new GenericRequestHandler(taskCommExecutor, mode)); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; // create a thread to listen for possible client available connections Thread t; if (mode.equals("late")) t = new LateBindingRequestListenerThread(port, httpService, sf); else t = new GenericRequestListenerThread(port, httpService, sf); System.out.println("Request Listener Thread created"); t.setDaemon(false); t.start(); // main thread should wait for the listener to exit before shutdown the // task executor pool t.join(); // shutdown task executor pool and wait for any taskCommExecutor thread // still running taskCommExecutor.shutdown(); while (!taskCommExecutor.isTerminated()) { } System.out.println("Finished all task communication executor threads"); System.out.println("Finished all tasks"); }
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 va 2 s . c o m 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:ca.uqac.info.monitor.BeepBeepMonitor.java
public static void main(String[] args) { int verbosity = 1, slowdown = 0, tcp_port = 0; boolean show_stats = false, to_stdout = false; String trace_filename = "", pipe_filename = "", event_name = "message"; final MonitorFactory mf = new MonitorFactory(); // In case we open a socket ServerSocket m_serverSocket = null; Socket m_connection = null;//from w ww . j a va 2 s . co m // Parse command line arguments Options options = setupOptions(); CommandLine c_line = setupCommandLine(args, options); assert c_line != null; if (c_line.hasOption("verbosity")) { verbosity = Integer.parseInt(c_line.getOptionValue("verbosity")); } if (verbosity > 0) { showHeader(); } if (c_line.hasOption("version")) { System.err.println("(C) 2008-2013 Sylvain Hall et al., Universit du Qubec Chicoutimi"); System.err.println("This program comes with ABSOLUTELY NO WARRANTY."); System.err.println("This is a free software, and you are welcome to redistribute it"); System.err.println("under certain conditions. See the file COPYING for details.\n"); System.exit(ERR_OK); } if (c_line.hasOption("h")) { showUsage(options); System.exit(ERR_OK); } if (c_line.hasOption("version")) { System.exit(ERR_OK); } if (c_line.hasOption("slowdown")) { slowdown = Integer.parseInt(c_line.getOptionValue("slowdown")); if (verbosity > 0) System.err.println("Slowdown factor: " + slowdown + " ms"); } if (c_line.hasOption("stats")) { show_stats = true; } if (c_line.hasOption("csv")) { // Will output data in CSV format to stdout to_stdout = true; } if (c_line.hasOption("eventname")) { // Set event name event_name = c_line.getOptionValue("eventname"); } if (c_line.hasOption("t")) { // Read events from a trace trace_filename = c_line.getOptionValue("t"); } if (c_line.hasOption("p")) { // Read events from a pipe pipe_filename = c_line.getOptionValue("p"); } if (c_line.hasOption("k")) { // Read events from a TCP port tcp_port = Integer.parseInt(c_line.getOptionValue("k")); } if (!trace_filename.isEmpty() && !pipe_filename.isEmpty()) { System.err.println("ERROR: you must specify at most one of trace file or named pipe"); showUsage(options); System.exit(ERR_ARGUMENTS); } @SuppressWarnings("unchecked") List<String> remaining_args = c_line.getArgList(); if (remaining_args.isEmpty()) { System.err.println("ERROR: no input formula specified"); showUsage(options); System.exit(ERR_ARGUMENTS); } // Instantiate the event notifier boolean notify = (verbosity > 0); EventNotifier en = new EventNotifier(notify); en.m_slowdown = slowdown; en.m_csvToStdout = to_stdout; // Create one monitor for each input file and add it to the notifier for (String formula_filename : remaining_args) { try { String formula_contents = FileReadWrite.readFile(formula_filename); Operator op = Operator.parseFromString(formula_contents); op.accept(mf); Monitor mon = mf.getMonitor(); Map<String, String> metadata = getMetadata(formula_contents); metadata.put("Filename", formula_filename); en.addMonitor(mon, metadata); } catch (IOException e) { e.printStackTrace(); System.exit(ERR_IO); } catch (Operator.ParseException e) { System.err.println("Error parsing input formula"); System.exit(ERR_PARSE); } } // Read trace and iterate // Opens file PipeReader pr = null; try { if (!pipe_filename.isEmpty()) { // We tell the pipe reader we read a pipe File f = new File(pipe_filename); if (verbosity > 0) System.err.println("Reading from pipe named " + f.getName()); pr = new PipeReader(new FileInputStream(f), en, false); } else if (!trace_filename.isEmpty()) { // We tell the pipe reader we read a regular file File f = new File(trace_filename); if (verbosity > 0) System.err.println("Reading from file " + f.getName()); pr = new PipeReader(new FileInputStream(f), en, true); } else if (tcp_port > 0) { // We tell the pipe reader we read from a socket if (verbosity > 0) System.err.println("Reading from TCP port " + tcp_port); m_serverSocket = new ServerSocket(tcp_port); m_connection = m_serverSocket.accept(); pr = new PipeReader(m_connection.getInputStream(), en, false); } else { // We tell the pipe reader we read from standard input if (verbosity > 0) System.err.println("Reading from standard input"); pr = new PipeReader(System.in, en, false); } } catch (FileNotFoundException ex) { // We print both trace and pipe since one of them must be empty System.err.println("ERROR: file not found " + trace_filename + pipe_filename); System.exit(ERR_IO); } catch (IOException e) { // Caused by socket error e.printStackTrace(); System.exit(ERR_IO); } pr.setSeparator("<" + event_name + ">", "</" + event_name + ">"); // Check parameters for the event notifier if (c_line.hasOption("no-trigger")) { en.m_notifyOnVerdict = false; } else { en.m_notifyOnVerdict = true; } if (c_line.hasOption("mirror")) { en.m_mirrorEventsOnStdout = true; } // Start event notifier en.reset(); Thread th = new Thread(pr); long clock_start = System.nanoTime(); th.start(); try { th.join(); // Wait for thread to finish } catch (InterruptedException e1) { // Thread is finished } if (tcp_port > 0 && m_serverSocket != null) { // We opened a socket; now we close it try { m_serverSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } long clock_end = System.nanoTime(); int ret_code = pr.getReturnCode(); switch (ret_code) { case PipeReader.ERR_EOF: if (verbosity > 0) System.err.println("\nEnd of file reached"); break; case PipeReader.ERR_EOT: if (verbosity > 0) System.err.println("\nEOT received on pipe: closing"); break; case PipeReader.ERR_OK: // Do nothing break; default: // An error System.err.println("Runtime error"); System.exit(ERR_RUNTIME); break; } if (show_stats) { if (verbosity > 0) { System.out.println("Messages: " + en.m_numEvents); System.out.println("Time: " + (int) (en.m_totalTime / 1000000f) + " ms"); System.out.println("Clock time: " + (int) ((clock_end - clock_start) / 1000000f) + " ms"); System.out.println("Max heap: " + (int) (en.heapSize / 1048576f) + " MB"); } else { // If stats are asked but verbosity = 0, only show time value // (both monitor and wall clock) System.out.print((int) (en.m_totalTime / 1000000f)); System.out.print(","); System.out.print((int) ((clock_end - clock_start) / 1000000f)); } } System.exit(ERR_OK); }
From source file:io.s4.zeno.SiteTest.java
public static void main(String[] arg) throws JSONException, KeeperException, IOException, InterruptedException { PropertyConfigurator.configure("log4j.properties"); String name = arg[0];/*from w ww . j a va2 s . c o m*/ String zkaddr = arg[1]; String zkbase = arg[2]; String specStr = arg[3]; ConfigMap spec = new JSONConfigMap(specStr); ZooKeeper zk = new ZooKeeper(zkaddr, 3000, zkhandler); zookeeper = new ZooKeeperHelper(zk, 5, 5000); zkpath = new ZKPaths(zkbase); ZooKeeperInfo zkinfo = new ZooKeeperInfo(); zkinfo.zookeeper = zookeeper; zkinfo.zkpath = zkpath; zkinfo.taskHolder = new NonblockingLockset(zookeeper, zkpath.taskBase); zkinfo.partsHolder = new NonblockingLockset(zookeeper, zkpath.partsBase); zkinfo.standbySequence = new DistributedSequence(zookeeper, zkpath.standbyBase); final Site site = new Site(name, spec); ZKCluster cluster = new ZKCluster(zookeeper, zkpath); ZKJobList jobList = new ZKJobList(site, zkinfo); ZKPartList partList = new ZKPartList(site, zkinfo); SiteInitializer init = new SiteInitializer(); site.setCluster(cluster); site.setJobList(jobList); site.setPartList(partList); site.setInitializer(init); class ZenoThreadGroup extends ThreadGroup { public ZenoThreadGroup() { super("ZenoThreadGroup"); } public void uncaughtException(Thread t, Throwable e) { System.out.println("ZENOTHREADGROUP CAUGHT AND EXCEPTION FROM THREAD " + t + ". SO EXITING. DETAILS:" + e + "\nCAUSED BY: " + e.getCause() + "\n"); e.printStackTrace(); System.exit(1); } } Thread t = new Thread(new ZenoThreadGroup(), new Runnable() { public void run() { site.start(); } }, "zenorunthread"); t.start(); System.out.println(); t.join(); }
From source file:com.easarrive.aws.plugins.common.service.impl.SimpleProducerConsumer.java
public static void main(String[] args) throws InterruptedException { final AWSCredentials credentials = new BasicAWSCredentials("AKIAIDPJMKK4UHLE3OVA", "A+cn+TT3tUs6xbto5k1IKkWwPLBq995aOkqKxZNY"); final String endpoint = "sqs.us-west-2.amazonaws.com"; final String queueName = "image"; final int producerCount = 10; final int consumerCount = 3; final int batchSize = 3; final int messageSizeByte = 10000; final int runTimeMinutes = 100; // configure the SQS client with enough connections for all producer and // consumer threads AmazonSQS sqsClient = new AmazonSQSClient(credentials, new ClientConfiguration().withMaxConnections(producerCount + consumerCount)); sqsClient.setEndpoint(endpoint);// w ww .java 2 s . co m String queueUrl = sqsClient.getQueueUrl(new GetQueueUrlRequest(queueName)).getQueueUrl(); // the flag to stop producer, consumer, and monitor threads AtomicBoolean stop = new AtomicBoolean(false); // start the producers final AtomicInteger producedCount = new AtomicInteger(); Thread[] producers = new Thread[producerCount]; for (int i = 0; i < producerCount; i++) { producers[i] = new BatchProducer(sqsClient, queueUrl, batchSize, messageSizeByte, producedCount, stop); producers[i].start(); } // start the consumers final AtomicInteger consumedCount = new AtomicInteger(); Thread[] consumers = new Thread[consumerCount]; for (int i = 0; i < consumerCount; i++) { consumers[i] = new BatchConsumer(sqsClient, queueUrl, batchSize, consumedCount, stop); consumers[i].start(); } // start the monitor (thread) Thread monitor = new Monitor(producedCount, consumedCount, stop); monitor.start(); // wait for the specified amount of time then stop Thread.sleep(TimeUnit.MINUTES.toMillis(Math.min(runTimeMinutes, MAX_RUNTIME_MINUTES))); stop.set(true); // join all threads for (int i = 0; i < producerCount; i++) producers[i].join(); for (int i = 0; i < consumerCount; i++) consumers[i].join(); monitor.interrupt(); monitor.join(); }
From source file:alluxio.examples.JournalCrashTest.java
/** * Runs the crash test./*from w w w . j a v a2 s. c om*/ * * Usage: * {@code java -cp * alluxio-<ALLUXIO-VERSION>-jar-with-dependencies.jar alluxio.examples.JournalCrashTest} * * @param args no arguments */ public static void main(String[] args) { // Parse the input args. if (!parseInputArgs(args)) { System.exit(EXIT_FAILED); } System.out.println("Stop the current Alluxio cluster..."); stopCluster(); // Set NO_STORE and NO_PERSIST so that this test can work without AlluxioWorker. sCreateFileOptions = CreateFileOptions.defaults().setWriteType(WriteType.NONE); // Set the max retry to avoid long pending for client disconnect. if (System.getProperty(Constants.MASTER_RETRY_COUNT) == null) { System.setProperty(Constants.MASTER_RETRY_COUNT, "10"); } System.out.println("Start Journal Crash Test..."); long startTimeMs = System.currentTimeMillis(); boolean ret = true; startMaster(); int rounds = 0; while (System.currentTimeMillis() - startTimeMs < sTotalTimeMs) { rounds++; long aliveTimeMs = (long) (Math.random() * sMaxAliveTimeMs) + 100; LOG.info("Round {}: Planning Master Alive Time {}ms.", rounds, aliveTimeMs); System.out.println("Round " + rounds + " : Launch Clients..."); sFileSystem = FileSystem.Factory.get(); try { sFileSystem.delete(new AlluxioURI(sTestDir)); } catch (Exception e) { // Test Directory not exist } // Launch all the client threads. setupClientThreads(); for (Thread thread : sClientThreadList) { thread.start(); } CommonUtils.sleepMs(LOG, aliveTimeMs); System.out.println("Round " + rounds + " : Crash Master..."); killMaster(); for (ClientThread clientThread : sClientThreadList) { clientThread.setIsStopped(true); } for (Thread thread : sClientThreadList) { try { thread.join(); } catch (InterruptedException e) { LOG.error("Error when waiting thread", e); } } System.out.println("Round " + rounds + " : Check Status..."); startMaster(); boolean checkSuccess = false; try { checkSuccess = checkStatus(); } catch (Exception e) { LOG.error("Failed to check status", e); } Utils.printPassInfo(checkSuccess); ret &= checkSuccess; } stopCluster(); System.exit(ret ? EXIT_SUCCESS : EXIT_FAILED); }