/** * Testing threads thoroughly seems to be a lot of fun, I am not sure yet how to properly do that. * This test tests priority order and total sum received is equal to total sum sent. It also * simulates clients random hanging. */ @Test public void testReceiveData() { DecorateCheckOrderAndCountSumMarshaller sumAppender = new DecorateCheckOrderAndCountSumMarshaller(); QueueWorker worker = new QueueWorker(sumAppender); Thread workerThread = new Thread(worker); // run 20 clients, 10.000 items will be generated per client as defined in // src/test/properties/app.properties for (int i = 0; i < 20; i++) { Runnable clientHangSimulator = null; if (i % 5 == 0) { // simulate occasional client hang for four of the total twenty clients and check worker is // not biased. clientHangSimulator = () -> { if (ThreadLocalRandom.current().nextInt(1001) % 1000 == 0) { try { Thread.sleep(500L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }; } executorService.execute(new DataGeneratorTask(clientHangSimulator)); } workerThread.start(); try { barrier.await(); System.out.println("Fired test"); Thread.sleep(1000); executorService.shutdown(); // runs actually much faster, may need update if item count per client is drastically // increased in app.properties executorService.awaitTermination(2 * 60, TimeUnit.SECONDS); System.out.println("exe service awaited"); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } try { workerThread.join(Long.MAX_VALUE); } catch (InterruptedException e) { e.printStackTrace(); } Assert.assertEquals( "Sum generated does not match sum received", sumAppender.getSum(), AppContext.getInstance().getTotalGeneratedAmount()); Assert.assertFalse("Worker didn't exit successfully", workerThread.isAlive()); }
@Override public void run() { System.out.format("[%s] Start running...\n", Thread.currentThread().getName()); runningThread = Thread.currentThread(); while (!Thread.currentThread().isInterrupted()) { System.out.format("[%s] counting for median %s\n", Thread.currentThread().getName(), median); count = calculateCount(numbers, median); try { barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); return; } } }
public static void main(String[] args) { CyclicBarrier cb = new CyclicBarrier(3, () -> out.println("first part is finished, let's keep going")); ExecutorService es = null; try { es = Executors.newFixedThreadPool(3); for (int i = 0; i < 3; i++) { es.execute(() -> _0417.task(cb)); } } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } finally { if (es != null) es.shutdown(); } }
public void run() { int count = SendWrapper.checkSeqNum(); while (count < Config.numPerRound) { job(); try { Thread.sleep(Config.ballThreadWait); } catch (InterruptedException e) { e.printStackTrace(); } count = SendWrapper.checkSeqNum(); } LogHelper.debug("arrive the limit, notifing others. "); this.stop(); try { barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } Thread.currentThread().interrupt(); }
@Override public void run() { Stopwatch watch = Stopwatch.createStarted(); int progress = 0; while (progress < carRace.getTrackLength()) { progress = progress + speed; } watch.stop(); timeElapsed = watch.elapsed(TimeUnit.MICROSECONDS); try { carRace.getFleet().put(this); log.debug( "Car: " + name + " has reached the finish line, time cost in microseconds : " + timeElapsed); carRace.getBarrier().await(); } catch (InterruptedException | BrokenBarrierException e) { this.log.warn(e.getMessage()); } }
@Override public void run() { AppContext appContext = AppContext.getInstance(); try { barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } for (int i = 0; i < AppContext.getInstance().getGeneratedItemCountPerConnection(); i++) { if (hangingSimulator != null) { hangingSimulator.run(); } lastTime += ThreadLocalRandom.current().nextInt(100); BigDecimal amount = new BigDecimal(ThreadLocalRandom.current().nextInt(100)); Item item = new Item(lastTime, amount); itemConsumer.accept(item); appContext.getClientRegistry().registerLastClientTime(id, lastTime); appContext.addToTotalGeneratedAmount(amount); } appContext.getClientRegistry().deregisterClient(id); System.out.println(MessageFormat.format("Client id {0} exited successfully.", id)); System.out.println("appContext = " + appContext.getWorkQueue().size()); }
/** Simulation for this thread to run through 1 work day */ public void run() { Random rand = new Random(); try { super.run(); // Wait for up to 30 mins elapseTime(rand.nextInt(TimeHelp.HALF_HOUR.ms() + 1)); /*-------ARRIVE AT WORK-------*/ System.out.printf( "%s: %s has arrived to the workplace\n", TimeTracker.currentTimeToString(), getName()); /*--------WAIT UNTIL TEAM MEETING-------*/ teamLead.arriveForMeeting(); // Wait until meeting while (!teamLead.isInConferenceRoom()) { elapseTime(TimeHelp.MINUTE.ms()); } conferenceRoom.arriveInRoom(true); elapseTime(TimeHelp.FIFTEEN_MINUTES.ms()); logMeetingTime(TimeHelp.FIFTEEN_MINUTES.ms()); System.out.printf( "%s: %s is leaving Team Meeting\n", TimeTracker.currentTimeToString(), getName()); /*--------WAIT UNTIL LUNCH BREAK-------*/ System.out.printf( "%s: %s is developing until lunch break.\n", TimeTracker.currentTimeToString(), getName()); // Wait until lunch while (TimeTracker.getCurrentTime() < TimeHelp.HOUR.ms() * 4) { int probability = rand.nextInt(5); if (probability == 1) { askQuestion(); } logWorkingTime(TimeHelp.MINUTE.ms()); elapseTime(TimeHelp.MINUTE.ms()); } /*--------LUNCH BREAK-------*/ System.out.println(TimeTracker.currentTimeToString() + ": " + getName() + " goes on lunch."); int breakTime = (int) ((Math.random() * TimeHelp.HALF_HOUR.ms()) + TimeHelp.HALF_HOUR.ms()); elapseTime(breakTime); // Eat lunch for 30-60 minutes System.out.println( TimeTracker.currentTimeToString() + ": " + getName() + " finished eating lunch."); logLunchBreakTime(breakTime); /*--------WAIT UNTIL 4pm MEETING-------*/ System.out.printf( "%s: %s is developing until the all hands meeting.\n", TimeTracker.currentTimeToString(), getName()); while (TimeTracker.getCurrentTime() < (TimeHelp.HOUR.ms() * 8)) { // If it isn't 4pm yet,\ int probability = rand.nextInt(100); if (probability == 1) { askQuestion(); } logWorkingTime(TimeHelp.MINUTE.ms()); Thread.sleep(TimeHelp.MINUTE.ms()); // Wait a minute } System.out.printf( "%s: %s is going to the all hands meeting\n", TimeTracker.currentTimeToString(), getName()); conferenceRoom.arriveInRoom(false); elapseTime(TimeHelp.FIFTEEN_MINUTES.ms()); logMeetingTime(TimeHelp.FIFTEEN_MINUTES.ms()); System.out.printf( "%s: %s has left the all hands meeting.%n", TimeTracker.currentTimeToString(), getName()); System.out.printf( "%s: %s is developing for the rest of the day\n", TimeTracker.currentTimeToString(), getName()); int remainingWorkTime = (int) ((Math.random() * 45) + 1); elapseTime(remainingWorkTime * TimeHelp.MINUTE.ms()); System.out.printf( "%s: %s has left work for the day\n", TimeTracker.currentTimeToString(), getName()); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } }