Example usage for java.lang Thread isAlive

List of usage examples for java.lang Thread isAlive

Introduction

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

Prototype

public final native boolean isAlive();

Source Link

Document

Tests if this thread is alive.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Thread thread = new MyThread();
    thread.start();/*  w w w  .j av a  2 s. co m*/

    if (thread.isAlive()) {
        System.out.println("Thread has not finished");
    } else {
        System.out.println("Finished");
    }
    long delayMillis = 5000; // 5 seconds
    thread.join(delayMillis);

    if (thread.isAlive()) {
        System.out.println("thread has not finished");
    } else {
        System.out.println("Finished");
    }
    thread.join();
}

From source file:ThreadDemo.java

public static void main(String args[]) throws Exception {

    Thread t = new Thread(new ThreadDemo());
    // this will call run() function
    t.start();//www  . j a  v  a 2s.  co  m
    // waits for this thread to die
    t.join();
    // tests if this thread is alive
    System.out.println("status = " + t.isAlive());
}

From source file:Main.java

public static void main(String args[]) throws Exception {

    Thread t = new Thread(new ThreadDemo());
    t.start();//from www  .  j  a  va2 s  .com

    t.join(2000, 500);
    //after waiting for 2000 milliseconds plus 500 nanoseconds ...
    System.out.print(t.getName());
    System.out.println(", status = " + t.isAlive());
}

From source file:Main.java

public static void main(String args[]) throws Exception {

    Thread t = new Thread(new ThreadDemo());
    t.start();//w w  w .  j  a  va2 s.  c o m
    // waits for this thread to die
    t.join();
    System.out.print(t.getName());
    // checks if this thread is alive
    System.out.println(", status = " + t.isAlive());
}

From source file:Main.java

public static void main(String args[]) throws Exception {

    Thread t = new Thread(new ThreadDemo());
    t.start();//ww w  .j a  v  a2  s.  c  om
    // waits at most 2000 milliseconds for this thread to die.
    t.join(2000);

    // after waiting for 2000 milliseconds...
    System.out.print(t.getName());

    System.out.println(", status = " + t.isAlive());
}

From source file:com.datastax.brisk.demo.pricer.Pricer.java

public static void main(String[] arguments) throws Exception {
    long latency, oldLatency;
    int epoch, total, oldTotal, keyCount, oldKeyCount;

    try {//  w w  w. j  a v a2s. c o  m
        session = new Session(arguments);
    } catch (IllegalArgumentException e) {
        printHelpMessage();
        return;
    }

    session.createKeySpaces();

    int threadCount = session.getThreads();
    Thread[] consumers = new Thread[threadCount];
    PrintStream out = session.getOutputStream();

    out.println("total,interval_op_rate,interval_key_rate,avg_latency,elapsed_time");

    int itemsPerThread = session.getKeysPerThread();
    int modulo = session.getNumKeys() % threadCount;

    // creating required type of the threads for the test
    for (int i = 0; i < threadCount; i++) {
        if (i == threadCount - 1)
            itemsPerThread += modulo; // last one is going to handle N + modulo items

        consumers[i] = new Consumer(itemsPerThread);
    }

    new Producer().start();

    // starting worker threads
    for (int i = 0; i < threadCount; i++) {
        consumers[i].start();
    }

    // initialization of the values
    boolean terminate = false;
    latency = 0;
    epoch = total = keyCount = 0;

    int interval = session.getProgressInterval();
    int epochIntervals = session.getProgressInterval() * 10;
    long testStartTime = System.currentTimeMillis();

    while (!terminate) {
        Thread.sleep(100);

        int alive = 0;
        for (Thread thread : consumers)
            if (thread.isAlive())
                alive++;

        if (alive == 0)
            terminate = true;

        epoch++;

        if (terminate || epoch > epochIntervals) {
            epoch = 0;

            oldTotal = total;
            oldLatency = latency;
            oldKeyCount = keyCount;

            total = session.operations.get();
            keyCount = session.keys.get();
            latency = session.latency.get();

            int opDelta = total - oldTotal;
            int keyDelta = keyCount - oldKeyCount;
            double latencyDelta = latency - oldLatency;

            long currentTimeInSeconds = (System.currentTimeMillis() - testStartTime) / 1000;
            String formattedDelta = (opDelta > 0) ? Double.toString(latencyDelta / (opDelta * 1000)) : "NaN";

            out.println(String.format("%d,%d,%d,%s,%d", total, opDelta / interval, keyDelta / interval,
                    formattedDelta, currentTimeInSeconds));
        }
    }
}

From source file:org.apache.cassandra.contrib.stress.Stress.java

public static void main(String[] arguments) throws Exception {
    long latency, oldLatency;
    int epoch, total, oldTotal, keyCount, oldKeyCount;

    try {/*  w w w .  ja  v a2s . c o  m*/
        session = new Session(arguments);
    } catch (IllegalArgumentException e) {
        printHelpMessage();
        return;
    }

    // creating keyspace and column families
    if (session.getOperation() == Stress.Operations.INSERT) {
        session.createKeySpaces();
    }

    int threadCount = session.getThreads();
    Thread[] consumers = new Thread[threadCount];
    PrintStream out = session.getOutputStream();

    out.println("total,interval_op_rate,interval_key_rate,avg_latency,elapsed_time");

    int itemsPerThread = session.getKeysPerThread();
    int modulo = session.getNumKeys() % threadCount;

    // creating required type of the threads for the test
    for (int i = 0; i < threadCount; i++) {
        if (i == threadCount - 1)
            itemsPerThread += modulo; // last one is going to handle N + modulo items

        consumers[i] = new Consumer(itemsPerThread);
    }

    new Producer().start();

    // starting worker threads
    for (int i = 0; i < threadCount; i++) {
        consumers[i].start();
    }

    // initialization of the values
    boolean terminate = false;
    latency = 0;
    epoch = total = keyCount = 0;

    int interval = session.getProgressInterval();
    int epochIntervals = session.getProgressInterval() * 10;
    long testStartTime = System.currentTimeMillis();

    while (!terminate) {
        Thread.sleep(100);

        int alive = 0;
        for (Thread thread : consumers)
            if (thread.isAlive())
                alive++;

        if (alive == 0)
            terminate = true;

        epoch++;

        if (terminate || epoch > epochIntervals) {
            epoch = 0;

            oldTotal = total;
            oldLatency = latency;
            oldKeyCount = keyCount;

            total = session.operations.get();
            keyCount = session.keys.get();
            latency = session.latency.get();

            int opDelta = total - oldTotal;
            int keyDelta = keyCount - oldKeyCount;
            double latencyDelta = latency - oldLatency;

            long currentTimeInSeconds = (System.currentTimeMillis() - testStartTime) / 1000;
            String formattedDelta = (opDelta > 0) ? Double.toString(latencyDelta / (opDelta * 1000)) : "NaN";

            out.println(String.format("%d,%d,%d,%s,%d", total, opDelta / interval, keyDelta / interval,
                    formattedDelta, currentTimeInSeconds));
        }
    }
}

From source file:org.apache.cassandra.stress.Stress.java

public static void main(String[] arguments) throws Exception {
    long latency, oldLatency;
    int epoch, total, oldTotal, keyCount, oldKeyCount;

    try {/*from w w w . j a  va2s.  co  m*/
        session = new Session(arguments);
    } catch (IllegalArgumentException e) {
        printHelpMessage();
        return;
    }

    // creating keyspace and column families
    if (session.getOperation() == Operations.INSERT || session.getOperation() == Operations.COUNTER_ADD) {
        session.createKeySpaces();
    }

    int threadCount = session.getThreads();
    Thread[] consumers = new Thread[threadCount];
    PrintStream out = session.getOutputStream();

    out.println("total,interval_op_rate,interval_key_rate,avg_latency,elapsed_time");

    int itemsPerThread = session.getKeysPerThread();
    int modulo = session.getNumKeys() % threadCount;

    // creating required type of the threads for the test
    for (int i = 0; i < threadCount; i++) {
        if (i == threadCount - 1)
            itemsPerThread += modulo; // last one is going to handle N + modulo items

        consumers[i] = new Consumer(itemsPerThread);
    }

    new Producer().start();

    // starting worker threads
    for (int i = 0; i < threadCount; i++) {
        consumers[i].start();
    }

    // initialization of the values
    boolean terminate = false;
    latency = 0;
    epoch = total = keyCount = 0;

    int interval = session.getProgressInterval();
    int epochIntervals = session.getProgressInterval() * 10;
    long testStartTime = System.currentTimeMillis();

    while (!terminate) {
        Thread.sleep(100);

        int alive = 0;
        for (Thread thread : consumers)
            if (thread.isAlive())
                alive++;

        if (alive == 0)
            terminate = true;

        epoch++;

        if (terminate || epoch > epochIntervals) {
            epoch = 0;

            oldTotal = total;
            oldLatency = latency;
            oldKeyCount = keyCount;

            total = session.operations.get();
            keyCount = session.keys.get();
            latency = session.latency.get();

            int opDelta = total - oldTotal;
            int keyDelta = keyCount - oldKeyCount;
            double latencyDelta = latency - oldLatency;

            long currentTimeInSeconds = (System.currentTimeMillis() - testStartTime) / 1000;
            String formattedDelta = (opDelta > 0) ? Double.toString(latencyDelta / (opDelta * 1000)) : "NaN";

            out.println(String.format("%d,%d,%d,%s,%d", total, opDelta / interval, keyDelta / interval,
                    formattedDelta, currentTimeInSeconds));
        }
    }
}

From source file:Main.java

public static void main(String args[]) {
    Thread thread1 = new Thread(new PipeOutput("Producer"));
    Thread thread2 = new Thread(new PipeInput("Consumer"));
    thread1.start();//www .j a v  a  2 s. c  om
    thread2.start();
    boolean thread1IsAlive = true;
    boolean thread2IsAlive = true;
    do {
        if (thread1IsAlive && !thread1.isAlive()) {
            thread1IsAlive = false;
        }
        if (thread2IsAlive && !thread2.isAlive()) {
            thread2IsAlive = false;
        }
    } while (thread1IsAlive || thread2IsAlive);
}

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

/**
 * @param args//from   w w  w. ja  v  a 2s. c  om
 * @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);
}