List of usage examples for java.lang Thread join
public final void join() throws InterruptedException
From source file:Main.java
public ThreadGroupDemo() { try {//from w w w. ja va 2 s. c om ThreadGroup pGroup = new ThreadGroup("Parent ThreadGroup"); ThreadGroup cGroup = new ThreadGroup(pGroup, "Child ThreadGroup"); Thread t1 = new Thread(pGroup, this); System.out.println("Starting " + t1.getName()); t1.start(); Thread t2 = new Thread(cGroup, this); System.out.println("Starting " + t2.getName()); t2.start(); // block until the other threads finish t1.join(); t2.join(); // child group destroyed cGroup.destroy(); System.out.println(cGroup.getName() + " destroyed"); // parent group destroyed pGroup.destroy(); System.out.println(pGroup.getName() + " destroyed"); } catch (InterruptedException ex) { System.out.println(ex.toString()); } }
From source file:cosmos.results.integration.CosmosIntegrationTest.java
@Test public void testWiki1() throws Exception { // Get the same wiki 3 times List<Thread> threads = Lists.newArrayList(); final List<Long> timings = Lists.newArrayList(); // Preload//from w w w . j av a2 s .c om Stopwatch sw = new Stopwatch(); sw.start(); getWiki1(); sw.stop(); long origLength = sw.elapsed(TimeUnit.MICROSECONDS); for (int i = 0; i < 3; i++) { threads.add(new Thread(new Runnable() { public void run() { try { Stopwatch sw = new Stopwatch(); sw.start(); getWiki1(); sw.stop(); timings.add(sw.elapsed(TimeUnit.MICROSECONDS)); } catch (Exception e) { throw new RuntimeException(e); } } })); } long start = System.currentTimeMillis(); for (Thread t : threads) { t.start(); } for (Thread t : threads) { t.join(); } long end = System.currentTimeMillis(); for (Long duration : timings) { Assert.assertTrue(origLength > duration); } }
From source file:org.t2framework.commons.util.LazyLoadingReference.java
public void test_loadHeavy() throws Exception { final LazyLoadingReference<String> target = new LazyLoadingReference<String>( new LazyLoadingReference.Factory<String>() { public String create() { return "hoge"; }//from w w w. j a v a2s . c o m }); final Random random = new Random(System.currentTimeMillis()); List<Thread> list = new ArrayList<Thread>(); for (int i = 0; i < 20; i++) { Runnable r = new Runnable() { public void run() { try { long l = random.nextLong() % 100; Thread.sleep(l < 0 ? l * -1 : l); assertEquals("hoge", target.get()); } catch (InterruptedException e) { e.printStackTrace(); } } }; Thread t = new Thread(r); list.add(t); t.start(); } for (Thread t : list) { t.join(); } }
From source file:ProgressDialog.java
private void setupEventHandlers() { addComponentListener(new ComponentAdapter() { public void componentShown(ComponentEvent event) { final Thread task = new Thread(runnable); task.start();/*from w ww . j a v a2s.c om*/ new Thread() { public void run() { try { task.join(); } catch (InterruptedException e) { } SwingUtilities.invokeLater(new Runnable() { public void run() { setVisible(false); } }); } }.start(); } }); }
From source file:org.statefulj.concurrency.ConcurrencyRunner.java
@Override public void run(String... args) throws Exception { unsafeValueRepository.save(unsafeValueDocument); logger.debug("+----------------------------------------------+"); logger.debug("| |"); logger.debug("| Start Demo |"); logger.debug("| |"); logger.debug("+----------------------------------------------+"); logger.debug(""); Runnable runnable = new Runnable() { @Override/* w w w . j ava 2 s .com*/ public void run() { for (int i = 0; i < 150; i++) { unsafeValueDocument.increment(); } } }; Thread t1 = new Thread(runnable); Thread t2 = new Thread(runnable); Thread t3 = new Thread(runnable); t1.start(); t2.start(); t3.start(); t1.join(); t2.join(); t3.join(); logger.debug("Value=" + this.unsafeValueRepository.findOne(unsafeValueDocument.getId()).getValue()); safeValueRepository.save(safeValueDocument); runnable = new Runnable() { @Override public void run() { for (int i = 0; i < 150; i++) { safeValueDocument.increment(); } } }; t1 = new Thread(runnable); t2 = new Thread(runnable); t3 = new Thread(runnable); t1.start(); t2.start(); t3.start(); t1.join(); t2.join(); t3.join(); logger.debug("Value=" + this.safeValueRepository.findOne(safeValueDocument.getId()).getValue()); logger.debug(""); logger.debug("+----------------------------------------------+"); logger.debug("| |"); logger.debug("| End Demo |"); logger.debug("| |"); logger.debug("+----------------------------------------------+"); }
From source file:com.espertech.esper.regression.view.TestMultithreadedTimeWin.java
public void testMultithreaded() throws Exception { int numSymbols = 1; int numThreads = 4; int numEventsPerThread = 50000; double timeWindowSize = 0.2; // Set up threads, statements and listeners setUp(numSymbols, numThreads, numEventsPerThread, timeWindowSize); // Start threads long startTime = System.currentTimeMillis(); for (Thread thread : threads) { thread.run();/*from www. j a v a 2 s . c om*/ } // Wait for completion for (Thread thread : threads) { thread.join(); } long endTime = System.currentTimeMillis(); // Check listener results long totalReceived = 0; for (ResultUpdateListener listener : listeners) { totalReceived += listener.getNumReceived(); assertFalse(listener.isCaughtRuntimeException()); } double numTimeWindowAdvancements = (endTime - startTime) / 1000 / timeWindowSize; log.info("Completed, expected=" + numEventsPerThread * numThreads + " numTimeWindowAdvancements=" + numTimeWindowAdvancements + " totalReceived=" + totalReceived); assertTrue(totalReceived < numEventsPerThread * numThreads + numTimeWindowAdvancements + 1); assertTrue(totalReceived >= numEventsPerThread * numThreads); }
From source file:com.alibaba.otter.shared.common.utils.cmd.Exec.java
public static Result execute(Process process, String cmd, String outputLog, byte[] input, File workingDir) throws Exception { // ???/*from w w w . ja v a2s .c o m*/ Thread inputThread = new InputPumper((input == null) ? new byte[] {} : input, process.getOutputStream()); StreamCollector stderr = null; StreamCollector stdout = null; FileOutputStream fileOutput = null; StreamAppender outputLogger = null; String errString = null; String outString = null; try { if (outputLog == null) { stdout = new StreamCollector(process.getInputStream()); stderr = new StreamCollector(process.getErrorStream()); stdout.start(); stderr.start(); } else { errString = "stderr output redirected to file " + outputLog; outString = "stdout output redirected to file " + outputLog; fileOutput = new FileOutputStream(outputLog); outputLogger = new StreamAppender(fileOutput); outputLogger.writeInput(process.getErrorStream(), process.getInputStream()); } inputThread.start(); final int exitCode = process.waitFor(); inputThread.join(); if (outputLogger != null) { outputLogger.finish(); } if (stdout != null) { stdout.join(); outString = stdout.toString(); } if (stderr != null) { stderr.join(); errString = stderr.toString(); } return new Result(cmd.toString(), outString, errString, exitCode); } finally { IOUtils.closeQuietly(fileOutput); if (process != null) { // evitons http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6462165 process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); process.destroy(); } } }
From source file:com.espertech.esper.regression.nwtable.TestTableMTGroupedAccessReadIntoTableWriteNewRowCreation.java
private void tryMT(int numEvents) throws Exception { String epl = "create table varTotal (key string primary key, total sum(int));\n" + "into table varTotal select theString, sum(intPrimitive) as total from SupportBean group by theString;\n" + "@Name('listen') select varTotal[p00].total as c0 from SupportBean_S0;\n"; epService.getEPAdministrator().getDeploymentAdmin().parseDeploy(epl); epService.getEPRuntime().sendEvent(new SupportBean("A", 10)); LinkedBlockingDeque<String> queueCreated = new LinkedBlockingDeque<String>(); WriteRunnable writeRunnable = new WriteRunnable(epService, numEvents, queueCreated); ReadRunnable readRunnable = new ReadRunnable(epService, numEvents, queueCreated); // start/*from w w w. j a v a 2 s .c o m*/ Thread t1 = new Thread(writeRunnable); Thread t2 = new Thread(readRunnable); t1.start(); t2.start(); // join log.info("Waiting for completion"); t1.join(); t2.join(); assertNull(writeRunnable.getException()); assertNull(readRunnable.getException()); }
From source file:es.uma.lcc.tasks.SendUpdateTask.java
private void handleAuthenticationError() { Thread t = new CookieRefresherThread(AccountManager.get(mMainActivity), mMainActivity); t.start();/*from w w w .j av a2 s.c om*/ try { t.join(); new SendUpdateTask(mOperations, mPicId, mMainActivity, false).execute(); } catch (InterruptedException e) { e.printStackTrace(); } }
From source file:com.xebialabs.overcast.command.CommandProcessor.java
public CommandResponse run(final Command command) { logger.debug("Executing command {}", command); try {/*from ww w. j a v a 2 s. c om*/ Process p = new ProcessBuilder(command.asList()).directory(new File(execDir)).start(); // We do this small trick to have stdout and stderr of the process on the console and // at the same time capture them to strings. ByteArrayOutputStream errors = new ByteArrayOutputStream(); ByteArrayOutputStream messages = new ByteArrayOutputStream(); Thread t1 = showProcessOutput(new TeeInputStream(p.getErrorStream(), errors), System.err); Thread t2 = showProcessOutput(new TeeInputStream(p.getInputStream(), messages), System.out); int code = p.waitFor(); t1.join(); t2.join(); CommandResponse response = new CommandResponse(code, errors.toString(), messages.toString()); if (!response.isSuccessful()) { throw new NonZeroCodeException(command, response); } return response; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("Cannot execute " + command.toString(), e); } catch (IOException e) { throw new RuntimeException("Cannot execute " + command.toString(), e); } }