Example usage for java.lang Thread sleep

List of usage examples for java.lang Thread sleep

Introduction

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

Prototype

public static native void sleep(long millis) throws InterruptedException;

Source Link

Document

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

Usage

From source file:SwingThreading.java

public static void main(String... args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            edt = new SwingThreading();
            edt.setVisible(true);//w  ww  .j  a v a  2 s  .co m

            new Thread(new Runnable() {
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                        }
                        edt.incrementLabel();
                    }
                }
            }).start();
        }
    });
}

From source file:interoperabilite.webservice.client.ClientEvictExpiredConnections.java

public static void main(String[] args) throws Exception {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(100);//from   ww w.j  av a2s.c o m
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).evictExpiredConnections()
            .evictIdleConnections(5L, TimeUnit.SECONDS).build();
    try {
        // create an array of URIs to perform GETs on
        String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core-ga/",
                "http://hc.apache.org/httpcomponents-client-ga/", };

        for (int i = 0; i < urisToGet.length; i++) {
            String requestURI = urisToGet[i];
            HttpGet request = new HttpGet(requestURI);

            System.out.println("Executing request " + requestURI);

            CloseableHttpResponse response = httpclient.execute(request);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        }

        PoolStats stats1 = cm.getTotalStats();
        System.out.println("Connections kept alive: " + stats1.getAvailable());

        // Sleep 10 sec and let the connection evictor do its job
        Thread.sleep(10000);

        PoolStats stats2 = cm.getTotalStats();
        System.out.println("Connections kept alive: " + stats2.getAvailable());

    } finally {
        httpclient.close();
    }
}

From source file:ProducerTool.java

public static void main(String[] args) {
    ArrayList<ProducerTool> threads = new ArrayList();
    ProducerTool producerTool = new ProducerTool();
    String[] unknown = CommandLineSupport.setOptions(producerTool, args);
    if (unknown.length > 0) {
        System.out.println("Unknown options: " + Arrays.toString(unknown));
        System.exit(-1);/*from w w  w  .  j a  va2s  .  c  o m*/
    }
    producerTool.showParameters();
    for (int threadCount = 1; threadCount <= parallelThreads; threadCount++) {
        producerTool = new ProducerTool();
        CommandLineSupport.setOptions(producerTool, args);
        producerTool.start();
        threads.add(producerTool);
    }

    while (true) {
        Iterator<ProducerTool> itr = threads.iterator();
        int running = 0;
        while (itr.hasNext()) {
            ProducerTool thread = itr.next();
            if (thread.isAlive()) {
                running++;
            }
        }
        if (running <= 0) {
            System.out.println("All threads completed their work");
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
        }
    }
}

From source file:ch.algotrader.event.TopicEventDumper.java

public static void main(String... args) throws Exception {

    SingleConnectionFactory jmsActiveMQFactory = new SingleConnectionFactory(
            new ActiveMQConnectionFactory("tcp://localhost:61616"));
    jmsActiveMQFactory.afterPropertiesSet();
    jmsActiveMQFactory.resetConnection();

    ActiveMQTopic topic = new ActiveMQTopic(">");

    DefaultMessageListenerContainer messageListenerContainer = new DefaultMessageListenerContainer();
    messageListenerContainer.setDestination(topic);
    messageListenerContainer.setConnectionFactory(jmsActiveMQFactory);
    messageListenerContainer.setSubscriptionShared(false);
    messageListenerContainer.setCacheLevel(DefaultMessageListenerContainer.CACHE_CONSUMER);

    messageListenerContainer.setMessageListener((MessageListener) message -> {
        try {/* w w  w  . j a v  a  2  s  .c o  m*/
            Destination destination = message.getJMSDestination();
            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                System.out.println(destination + " -> " + textMessage.getText());
            } else if (message instanceof BytesMessage) {
                BytesMessage bytesMessage = (BytesMessage) message;
                byte[] bytes = new byte[(int) bytesMessage.getBodyLength()];
                bytesMessage.readBytes(bytes);
                System.out.println(destination + " -> " + new String(bytes, Charsets.UTF_8));
            }
        } catch (JMSException ex) {
            throw new UnrecoverableCoreException(ex);
        }
    });

    messageListenerContainer.initialize();
    messageListenerContainer.start();

    System.out.println("Dumping messages from all topics");

    Runtime.getRuntime().addShutdownHook(new Thread(messageListenerContainer::stop));

    Thread.sleep(Long.MAX_VALUE);
}

From source file:io.reappt.adapters.kafka.KafkaAdapter.java

public static void main(String args[])
        throws InterruptedException, IOException, KeyManagementException, NoSuchAlgorithmException {
    KafkaAdapter producer = new KafkaAdapter();
    producer.start();//from   w  ww.  ja  v  a  2  s.c  om
    producer.listen();
    while (true) {
        Thread.sleep(1000);
    }
}

From source file:SplashScreenCreate.java

public static void main(String[] args) {
    final Display display = new Display();
    final int[] count = new int[] { 4 };
    final Image image = new Image(display, 300, 300);
    GC gc = new GC(image);
    gc.setBackground(display.getSystemColor(SWT.COLOR_CYAN));
    gc.fillRectangle(image.getBounds());
    gc.drawText("Splash Screen", 10, 10);
    gc.dispose();/*from w ww.  j  a  v a 2  s.co  m*/
    final Shell splash = new Shell(SWT.ON_TOP);
    final ProgressBar bar = new ProgressBar(splash, SWT.NONE);
    bar.setMaximum(count[0]);
    Label label = new Label(splash, SWT.NONE);
    label.setImage(image);
    FormLayout layout = new FormLayout();
    splash.setLayout(layout);
    FormData labelData = new FormData();
    labelData.right = new FormAttachment(100, 0);
    labelData.bottom = new FormAttachment(100, 0);
    label.setLayoutData(labelData);
    FormData progressData = new FormData();
    progressData.left = new FormAttachment(0, 5);
    progressData.right = new FormAttachment(100, -5);
    progressData.bottom = new FormAttachment(100, -5);
    bar.setLayoutData(progressData);
    splash.pack();
    Rectangle splashRect = splash.getBounds();
    Rectangle displayRect = display.getBounds();
    int x = (displayRect.width - splashRect.width) / 2;
    int y = (displayRect.height - splashRect.height) / 2;
    splash.setLocation(x, y);
    splash.open();
    display.asyncExec(new Runnable() {
        public void run() {
            Shell[] shells = new Shell[count[0]];
            for (int i = 0; i < count[0]; i++) {
                shells[i] = new Shell(display);
                shells[i].setSize(300, 300);
                shells[i].addListener(SWT.Close, new Listener() {
                    public void handleEvent(Event e) {
                        --count[0];
                    }
                });
                bar.setSelection(i + 1);
                try {
                    Thread.sleep(1000);
                } catch (Throwable e) {
                }
            }
            splash.close();
            image.dispose();
            for (int i = 0; i < count[0]; i++) {
                shells[i].open();
            }
        }
    });
    while (count[0] != 0) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:com.dlmu.heipacker.crawler.client.ClientEvictExpiredConnections.java

public static void main(String[] args) throws Exception {
    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    cm.setMaxTotal(100);/*  w w w. j a va 2  s. co  m*/

    HttpClient httpclient = new DefaultHttpClient(cm);
    try {
        // create an array of URIs to perform GETs on
        String[] urisToGet = { "http://jakarta.apache.org/", "http://jakarta.apache.org/commons/",
                "http://jakarta.apache.org/commons/httpclient/",
                "http://svn.apache.org/viewvc/jakarta/httpcomponents/" };

        IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
        connEvictor.start();

        for (int i = 0; i < urisToGet.length; i++) {
            String requestURI = urisToGet[i];
            HttpGet req = new HttpGet(requestURI);

            System.out.println("executing request " + requestURI);

            HttpResponse rsp = httpclient.execute(req);
            HttpEntity entity = rsp.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(rsp.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            System.out.println("----------------------------------------");

            EntityUtils.consume(entity);
        }

        // Sleep 10 sec and let the connection evictor do its job
        Thread.sleep(20000);

        // Shut down the evictor thread
        connEvictor.shutdown();
        connEvictor.join();

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:me.Aron.Heinecke.fbot.fbot.java

public static void main(String[] args) {
    // initialize logger
    log = new cLogger(log_file_name, sdf);
    log.info("main", "#######################");
    log.info("main", "Starting fbot v.2.7.4");
    // log.info("main", "DEV-BUILD FOR TESTING PURPOSE!");
    log.info("main", "support.proctet@t-online.de");

    try {// load configuration, start socket, converter, threads, register
         // exit code
        config = new cConfig("fbot_config.cfg", "/me/Aron/Heinecke/fbot/default.cfg", log, true);
        config.load(true);//ww  w  . ja  v  a  2s . com
        loadConf();

        conv = new Converter();
        soc = new Socket();

        registerExitFunction();
        registerThreads();

    } catch (Exception e) { // catches all errors and log them, otherwise
        // crashes in productive state aren't
        // reconstructible
        log.severe("main", "Catched error in last instance!");
        log.exception("main", e);
    }
    while (true) {
        try {
            // Make sure that the Java VM don't quit this program.
            Thread.sleep(100);
        } catch (Exception e) {/* ignore */
        }
    }
}

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 {//from w  ww.ja  v a 2 s .c om
        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:com.microsoft.kafkaavailability.App.java

public static void main(String[] args) throws IOException, MetaDataManagerException, InterruptedException {
    System.out.println("Starting KafkaAvailability Tool");
    IPropertiesManager appPropertiesManager = new PropertiesManager<AppProperties>("appProperties.json",
            AppProperties.class);
    appProperties = (AppProperties) appPropertiesManager.getProperties();
    Options options = new Options();
    options.addOption("r", "run", true,
            "Number of runs. Don't use this argument if you want to run infintely.");
    options.addOption("s", "sleep", true,
            "Time (in milliseconds) to sleep between each run. Default is 300000");
    Option clusterOption = Option.builder("c").hasArg().required(true).longOpt("cluster")
            .desc("(REQUIRED) Cluster name").build();
    options.addOption(clusterOption);/* w ww  .j ava 2  s.c  o  m*/
    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        int howManyRuns;

        m_cluster = line.getOptionValue("cluster");
        MDC.put("cluster", m_cluster);

        if (line.hasOption("sleep")) {
            m_sleepTime = Integer.parseInt(line.getOptionValue("sleep"));
        }
        if (line.hasOption("run")) {
            howManyRuns = Integer.parseInt(line.getOptionValue("run"));
            for (int i = 0; i < howManyRuns; i++) {
                InitMetrics();
                RunOnce();
                Thread.sleep(m_sleepTime);
            }
        } else {
            while (true) {
                InitMetrics();
                RunOnce();
                Thread.sleep(m_sleepTime);
            }
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        formatter.printHelp("KafkaAvailability", options);
    }

}