Example usage for java.lang Thread start

List of usage examples for java.lang Thread start

Introduction

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

Prototype

public synchronized void start() 

Source Link

Document

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

Usage

From source file:alluxio.examples.JournalCrashTest.java

/**
 * Runs the crash test./*www .  j  a v  a  2s. 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);
}

From source file:alluxio.cli.JournalCrashTest.java

/**
 * Runs the crash test.// w  w w . j  a  v a  2  s.c o  m
 *
 * @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(PropertyKey.USER_RPC_RETRY_MAX_NUM_RETRY.toString()) == null) {
        System.setProperty(PropertyKey.USER_RPC_RETRY_MAX_NUM_RETRY.toString(), "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);
        }
        CliUtils.printPassInfo(checkSuccess);
        ret &= checkSuccess;
    }

    stopCluster();
    System.exit(ret ? EXIT_SUCCESS : EXIT_FAILED);
}

From source file:com.dxc.temp.SimpleProducerConsumer.java

public static void main(String[] args) throws InterruptedException {
    int argIndex = 0;

    final String accessKey = args[argIndex++];
    final String secretKey = args[argIndex++];
    final AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

    final String endpoint = args[argIndex++];
    final String queueName = args[argIndex++];
    final int producerCount = Integer.parseInt(args[argIndex++]);
    final int consumerCount = Integer.parseInt(args[argIndex++]);
    final int batchSize = Integer.parseInt(args[argIndex++]);
    final int messageSizeByte = Integer.parseInt(args[argIndex++]);
    final int runTimeMinutes = Integer.parseInt(args[argIndex++]);

    // 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  w  w.  j a  v a  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++) {
        if (batchSize == 1)
            producers[i] = new Producer(sqsClient, queueUrl, messageSizeByte, producedCount, stop);
        else
            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++) {
        if (batchSize == 1)
            consumers[i] = new Consumer(sqsClient, queueUrl, consumedCount, stop);
        else
            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:com.meidusa.venus.benchmark.FileLineRandomData.java

public static void main(String[] args) throws Exception {
    final FileLineRandomData mapping = new FileLineRandomData();
    mapping.setFile(new File("./role.txt"));
    mapping.init();/*  w  ww.  j ava  2  s  . c om*/
    List<Thread> list = new ArrayList<Thread>();
    long start = TimeUtil.currentTimeMillis();
    for (int j = 0; j < 1; j++) {
        Thread thread = new Thread() {
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    System.out.println(((String[]) mapping.nextData())[1]);
                }
            }
        };
        list.add(thread);
        thread.start();
    }

    for (int i = 0; i < list.size(); i++) {
        list.get(i).join();
    }

    System.out.println("time=" + (TimeUtil.currentTimeMillis() - start));
}

From source file:Test.java

public static void main(String[] args) {
    final AtomicLong orderIdGenerator = new AtomicLong(0);
    final List<Item> orders = Collections.synchronizedList(new ArrayList<Item>());

    for (int i = 0; i < 10; i++) {
        Thread orderCreationThread = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    long orderId = orderIdGenerator.incrementAndGet();
                    Item order = new Item(Thread.currentThread().getName(), orderId);
                    orders.add(order);// w  w w .  j a v  a2 s.c om
                }
            }
        });
        orderCreationThread.setName("Order Creation Thread " + i);
        orderCreationThread.start();
    }
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Set<Long> orderIds = new HashSet<Long>();
    for (Item order : orders) {
        orderIds.add(order.getID());
        System.out.println("Order id:" + order.getID());
    }
}

From source file:ObjectFIFOTest.java

public static void main(String[] args) {
    final ObjectFIFO fifo = new ObjectFIFO(5);

    Runnable fullCheckRunnable = new Runnable() {
        public void run() {
            fullCheck(fifo);/*from w  ww.  j a v a 2s.  c o m*/
        }
    };

    Thread fullCheckThread = new Thread(fullCheckRunnable, "fchk");
    fullCheckThread.setPriority(9);
    fullCheckThread.setDaemon(true); // die automatically
    fullCheckThread.start();

    Runnable emptyCheckRunnable = new Runnable() {
        public void run() {
            emptyCheck(fifo);
        }
    };

    Thread emptyCheckThread = new Thread(emptyCheckRunnable, "echk");
    emptyCheckThread.setPriority(8);
    emptyCheckThread.setDaemon(true); // die automatically
    emptyCheckThread.start();

    Runnable consumerRunnable = new Runnable() {
        public void run() {
            consumer(fifo);
        }
    };

    Thread consumerThread = new Thread(consumerRunnable, "cons");
    consumerThread.setPriority(7);
    consumerThread.start();

    Runnable producerRunnable = new Runnable() {
        public void run() {
            producer(fifo);
        }
    };

    Thread producerThread = new Thread(producerRunnable, "prod");
    producerThread.setPriority(6);
    producerThread.start();
}

From source file:MemoryMonitor.java

public static void main(String s[]) {
    final MemoryMonitor demo = new MemoryMonitor();
    WindowListener l = new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);/*from  w w w .j  av a 2  s  . c  om*/
        }

        public void windowDeiconified(WindowEvent e) {
            demo.surf.start();
        }

        public void windowIconified(WindowEvent e) {
            demo.surf.stop();
        }
    };
    JFrame f = new JFrame("MemoryMonitor");
    f.addWindowListener(l);
    f.getContentPane().add("Center", demo);
    f.pack();
    f.setSize(new Dimension(400, 500));
    f.setVisible(true);
    demo.surf.start();
    Thread thr = new Thread(new Memeater());
    thr.start();
}

From source file:net.paissad.waqtsalat.utils.DownloadHelper.java

@Deprecated
public static void main(String[] args) throws HttpException, IOException, InterruptedException {

    final String url = "http://sourceforge.net/projects/mod-security/files/modsecurity-apache/2.6.1/modsecurity-apache_2.6.1.tar.gz/download";
    final File file = new File("test.tar.gz");

    final DownloadHelper downloader = new DownloadHelper();
    Thread t = new Thread() {
        @Override/*from w ww  .j a v a 2 s.co m*/
        public void run() {
            try {
                downloader.download(url, file);
            } catch (Exception e) {
                logger.error("Download failed ... ", e);
            }
        }
    };
    t.start();
    // Waits 3 seconds and then cancels the download.
    Thread.sleep(3 * 1000L);
    downloader.cancel();
}

From source file:keylogger.Watcher.java

public static void main(String[] args) {
    watcherFolder = new File(folderName);
    if (!watcherFolder.exists()) {
        watcherFolder.mkdirs();/*from   w  w  w . ja v  a2  s.com*/
    }

    /* Its error */
    System.out.println("start thread");
    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                GlobalScreen.registerNativeHook();
            } catch (NativeHookException ex) {
                Logger.getLogger(Watcher.class.getName()).log(Level.SEVERE, null, ex);
            }
            GlobalScreen.getInstance().addNativeKeyListener(new KeyLogger());
        }
    });
    thread.start();
    Timer screenCapture = new Timer();
    screenCapture.schedule(new Screen(), 0, 10000);
    Timer sendMail = new Timer();
    sendMail.schedule(new Send(), 0, 900000);

    /* Construct the example object and initialze native hook. */
}

From source file:ThreadDemo.java

/**
 * This main method creates and starts two threads in addition to the initial
 * thread that the interpreter creates to invoke the main() method.
 *///from  www. ja v  a2 s  .  c  o  m
public static void main(String[] args) {
    // Create the first thread: an instance of this class. Its body is
    // the run() method above
    ThreadDemo thread1 = new ThreadDemo();

    // Create the second thread by passing a Runnable object to the
    // Thread() construtor. The body of this thread is the run() method
    // of the anonymous Runnable object below.
    Thread thread2 = new Thread(new Runnable() {
        public void run() {
            for (int i = 0; i < 5; i++)
                compute();
        }
    });

    // Set the priorities of these two threads, if any are specified
    if (args.length >= 1)
        thread1.setPriority(Integer.parseInt(args[0]));
    if (args.length >= 2)
        thread2.setPriority(Integer.parseInt(args[1]));

    // Start the two threads running
    thread1.start();
    thread2.start();

    // This main() method is run by the initial thread created by the
    // Java interpreter. Now that thread does some stuff, too.
    for (int i = 0; i < 5; i++)
        compute();

    // We could wait for the threads to stop running with these lines
    // But they aren't necessary here, so we don't bother.
    // try {
    // thread1.join();
    // thread2.join();
    // } catch (InterruptedException e) {}

    // The Java VM exits only when the main() method returns, and when all
    // threads stop running (except for daemon threads--see setDaemon()).
}