Example usage for java.lang Thread join

List of usage examples for java.lang Thread join

Introduction

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

Prototype

public final void join() throws InterruptedException 

Source Link

Document

Waits for this thread to die.

Usage

From source file:fresto.datastore.EventLogWriter.java

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        LOGGER.severe("Argumests needed : <frontHost> <frontPort>");
        System.exit(1);//w  w w.ja  v a 2 s  .  c  o m
    } else {
        frontHost = args[0];
        frontPort = args[1];
        LOGGER.info("Connecting... " + frontHost + ":" + frontPort + " with SUB");
    }

    final ZMQ.Context context = ZMQ.context(1);

    final FrestoEventQueue frestoEventQueue = new FrestoEventQueue();

    final Thread queueMonitorThread = new Thread() {
        Logger _LOGGER = Logger.getLogger("logWriteThread");

        @Override
        public void run() {
            while (work) {
                try {
                    _LOGGER.info("frestoEventQueue size = " + frestoEventQueue.size());
                    Thread.sleep(1000);
                } catch (InterruptedException ie) {
                }

            }
        }
    };

    final Thread logWriteThread = new Thread() {
        Logger _LOGGER = Logger.getLogger("logWriteThread");

        @Override
        public void run() {
            //FrestoStopWatch _watch = new FrestoStopWatch();
            //FrestoStopWatch _durationWatch = new FrestoStopWatch();

            EventLogWriter eventLogWriter = new EventLogWriter();

            // Open database
            //eventLogWriter.openTitanGraph();

            ZMQ.Socket receiver = null;
            //if("pull".equalsIgnoreCase(subOrPull)) {
            //   receiver = context.socket(ZMQ.PULL);
            //   receiver.connect("tcp://" + frontHost + ":" + frontPort);
            //} else if("sub".equalsIgnoreCase(subOrPull)) {
            receiver = context.socket(ZMQ.SUB);
            receiver.connect("tcp://" + frontHost + ":" + frontPort);
            receiver.subscribe("".getBytes());
            //} else {
            //   LOGGER.severe(subOrPull + " is not supported.");
            //   System.exit(1);
            //}

            //Consume socket data
            frestoEventQueue.setPullerSocket(receiver);
            frestoEventQueue.start();

            int waitingEventCount = 0;
            //int count = 0;
            //long elapsedTime = 0;
            //long duration = 0;

            //_durationWatch.start();

            while (work) {

                // To wait until at least one event in queue
                if (frestoEventQueue.isEmpty()) {
                    try {
                        //_LOGGER.info("FrestoEventQueue is empty. Waiting " + SLEEP_TIME + "ms...");
                        Thread.sleep(SLEEP_TIME);
                        continue;
                    } catch (InterruptedException ie) {
                    }
                }

                waitingEventCount = frestoEventQueue.size();

                for (int i = 0; i < waitingEventCount; i++) {
                    //_watch.start();
                    //count++;

                    FrestoEvent frestoEvent = frestoEventQueue.poll();

                    try {
                        eventLogWriter.writeEventData(frestoEvent.topic, frestoEvent.eventBytes);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        //
                    }

                    //elapsedTime += _watch.stop();
                    //duration += _durationWatch.stop();

                    //if(count == maxCommitCount) {
                    //   eventLogWriter.commitGraph();
                    //   _LOGGER.info(count + " events processed for " + elapsedTime + " ms. (total time " + duration + " ms.) Remaining events " + frestoEventQueue.size());
                    //   
                    //   count = 0;
                    //   elapsedTime = 0;
                    //   duration = 0;
                    //   // Stop FOR clause
                    //}
                }

                //eventLogWriter.commitGraph();

                _LOGGER.info("Remaining events " + frestoEventQueue.size());

                //count = 0;
                //elapsedTime = 0;
                //duration = 0;
            }
            _LOGGER.info("Shutting down...");

            //if(g.isOpen()) {
            //   g.commit();
            //   g.shutdown();
            //}

            receiver.close();
            context.term();

            _LOGGER.info("Good bye.");
        }
    };

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            System.out.println(" Interrupt received, killing logger");
            // To break while clause
            frestoEventQueue.stopWork();
            work = false;

            try {
                logWriteThread.join();
                frestoEventQueue.join();
                //queueMonitorThread.join();

            } catch (InterruptedException e) {
                //
            }
        }
    });

    //queueMonitorThread.start();
    logWriteThread.start();

}

From source file:de.uniwue.info6.database.SQLParserTest.java

public static void main(String[] args) throws Exception {
    String test = "Dies ist ein einfacher Test";
    System.out.println(StringTools.forgetOneWord(test));

    System.exit(0);/*from   w  w  w .j a v a  2s  . c  om*/
    // SimpleTupel<String, Integer> test1 =  new SimpleTupel<String, Integer>("test1", 1);
    // SimpleTupel<String, Integer> test2 =  new SimpleTupel<String, Integer>("test1", 12);

    // ArrayList<SimpleTupel<String, Integer>> test = new ArrayList<SimpleTupel<String, Integer>>();
    // test.add(test1);
    // System.out.println(test1.equals(test2));
    // System.exit(0);

    final boolean resetDb = true;
    // Falls nur nach einer bestimmten Aufgabe gesucht wird
    final Integer exerciseID = 39;
    final Integer scenarioID = null;
    final int threadSize = 1;

    final EquivalenceLock<Long[]> equivalenceLock = new EquivalenceLock<Long[]>();
    final Long[] performance = new Long[] { 0L, 0L };

    // ------------------------------------------------ //
    final ScenarioDao scenarioDao = new ScenarioDao();
    final ExerciseDao exerciseDao = new ExerciseDao();
    final ExerciseGroupDao groupDao = new ExerciseGroupDao();
    final UserDao userDao = new UserDao();
    final ArrayList<Thread> threads = new ArrayList<Thread>();

    // ------------------------------------------------ //
    try {
        ConnectionManager.offline_instance();
        if (resetDb) {
            Cfg.inst().setProp(MAIN_CONFIG, IMPORT_EXAMPLE_SCENARIO, true);
            Cfg.inst().setProp(MAIN_CONFIG, FORCE_RESET_DATABASE, true);
            new GenerateData().resetDB();
            ConnectionTools.inst().addSomeTestData();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    // ------------------------------------------------ //

    final List<Scenario> scenarios = scenarioDao.findAll();

    try {
        // ------------------------------------------------ //
        String userID;
        for (int i = 2; i < 100; i++) {
            userID = "user_" + i;
            User userToInsert = new User();
            userToInsert.setId(userID);
            userToInsert.setIsAdmin(false);
            userDao.insertNewInstance(userToInsert);
        }
        // ------------------------------------------------ //

        for (int i = 0; i < threadSize; i++) {
            Thread thread = new Thread() {

                public void run() {
                    // ------------------------------------------------ //
                    try {
                        Thread.sleep(new Random().nextInt(30));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // ------------------------------------------------ //

                    User user = userDao.getRandom();
                    Thread.currentThread().setName(user.getId());
                    System.err.println(
                            "\n\nINFO (ueps): Thread '" + Thread.currentThread().getName() + "' started\n");

                    // ------------------------------------------------ //

                    for (Scenario scenario : scenarios) {
                        if (scenarioID != null && !scenario.getId().equals(scenarioID)) {
                            continue;
                        }

                        System.out.println(StringUtils.repeat("#", 90));
                        System.out.println("SCENARIO: " + scenario.getId());

                        // ------------------------------------------------ //
                        for (ExerciseGroup group : groupDao.findByScenario(scenario)) {
                            System.out.println(StringUtils.repeat("#", 90));
                            System.out.println("GROUP: " + group.getId());
                            System.out.println(StringUtils.repeat("#", 90));
                            List<Exercise> exercises = exerciseDao.findByExGroup(group);

                            // ------------------------------------------------ //
                            for (Exercise exercise : exercises) {
                                if (exerciseID != null && !exercise.getId().equals(exerciseID)) {
                                    continue;
                                }
                                long startTime = System.currentTimeMillis();

                                for (int i = 0; i < 100; i++) {
                                    String userID = "user_" + new Random().nextInt(100000);
                                    User userToInsert = new User();
                                    userToInsert.setId(userID);
                                    userToInsert.setIsAdmin(false);
                                    userDao.insertNewInstance(userToInsert);
                                    user = userDao.getById(userID);

                                    List<SolutionQuery> solutions = new ExerciseDao().getSolutions(exercise);
                                    String solution = solutions.get(0).getQuery();
                                    ExerciseController exc = new ExerciseController().init_debug(scenario,
                                            exercise, user);
                                    exc.setUserString(solution);

                                    String fd = exc.getFeedbackList().get(0).getFeedback();
                                    System.out.println("Used Query: " + solution);
                                    if (fd.trim().toLowerCase().equals("bestanden")) {
                                        System.out.println(exercise.getId() + ": " + fd);
                                    } else {
                                        System.err.println(exercise.getId() + ": " + fd + "\n");
                                    }
                                    System.out.println(StringUtils.repeat("-", 90));
                                }

                                long elapsedTime = System.currentTimeMillis() - startTime;

                                // if (i > 5) {
                                //   try {
                                //     equivalenceLock.lock(performance);
                                //     performance[0] += elapsedTime;
                                //     performance[1]++;
                                //   } catch (Exception e) {
                                //   } finally {
                                //     equivalenceLock.release(performance);
                                //   }
                                // }
                            }
                        }
                    }

                    System.err
                            .println("INFO (ueps): Thread '" + Thread.currentThread().getName() + "' stopped");
                }
            };
            thread.start();
            threads.add(thread);
        }

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

        // try {
        //   equivalenceLock.lock(performance);

        //   long elapsedTime = (performance[0] / performance[1]);
        //   System.out.println("\n" + String.format("perf : %d.%03dsec", elapsedTime / 1000, elapsedTime % 1000));
        // } catch (Exception e) {
        // } finally {
        //   equivalenceLock.release(performance);
        // }

    } finally {
    }
}

From source file:Main.java

public static void waitFor(Collection<? extends Thread> c) throws InterruptedException {
    for (Thread t : c)
        t.join();
}

From source file:Main.java

public static void join(Thread thread) {
    try {//from   w  w w . jav a  2s.  c  om
        thread.join();
    } catch (InterruptedException e) {
    }
}

From source file:Main.java

public static void joinThreads(Thread[] threads) throws InterruptedException {
    for (int i = 0; i < threads.length; i++) {
        Thread thread = threads[i];
        thread.join();
    }//from  www  . j  a  v a2 s .c o m
}

From source file:Main.java

public static void join(Thread t) {
    try {/*from   w ww. j av  a  2s .co m*/
        t.join();
    } catch (InterruptedException e) {
        // ignore
    }
}

From source file:Main.java

/**
 * Join all the threads.// www  .  j  av  a  2s  .  c o m
 *
 * @param threads The threads to join.
 *
 * @throws InterruptedException If the thread is interrupted during joining.
 */
public static void joinAll(Iterable<Thread> threads) throws InterruptedException {
    for (Thread thread : threads) {
        thread.join();
    }
}

From source file:Main.java

public static void join(Thread thread) {
    try {//from  w w w  .j a va  2s .c o  m
        thread.join();
    } catch (InterruptedException inex) {
        // ignore
    }
}

From source file:Main.java

public static boolean doJoin(Thread thread) {
    try {//from www  . j  a v a2 s  .  c  om
        thread.join();
        return true;
    } catch (InterruptedException e) {
        return false;
    }

}

From source file:Main.java

/**
 * Waits for this thread to die./*from   ww w.j  ava 2  s.c  o  m*/
 *
 * @param thread the thread to wait for
 * @return true if success, false if interrupted
 */
public static final boolean join(Thread thread) {
    try {
        thread.join();
        return true;
    } catch (Exception e) {
        return false;
    }
}