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:com.alibaba.demo.NapoliClientDemo.java

public static void main(String[] args) throws Exception {
    log.info("demo start.");
    NapoliClientDemo demo = new NapoliClientDemo();
    demo.init();/* w ww  .  j a v  a2 s  .c om*/

    demo.receiver0.setWorker(new ShowMessageWorker("receiver0"));
    //demo.receiver1.setWorker(new ShowMessageWorker("receiver1"));
    //demo.receiver2.setWorker(new ShowMessageWorker("receiver2"));

    demo.receiver0.start();
    //demo.receiver1.start();
    //demo.receiver2.start();
    log.info("receiver started.");

    log.info("start send message");
    //topicqueue
    //demo.vFilterSender.send("a");

    for (int i = 0; i < DEFAULT_MSG_COUNT; i++) {
        try {
            // ???Topic
            // demo.vSender.send(new Person("vt", 33, "23404--22"));
            //log.info("Send to Topic: vt3323404--22");
            // ???Queue
            demo.qSender.send(new Person("queue", 33, "23404--22"));
            log.info("Send to Queue: queue3323404--22");

            Thread.sleep(300);
        } catch (Exception e) {
            log.error("Send Error: " + e);
        }
    }
}

From source file:io.prometheus.client.examples.random.Main.java

public static void main(final String[] arguments) {
    Registry.defaultInitialize();
    final Server server = new Server(8181);
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);/*from ww w. ja v a  2 s .  c o m*/
    context.addServlet(new ServletHolder(new MetricsServlet()), "/");

    new Thread() {
        @Override
        public void run() {
            final RandomDataImpl randomData = new RandomDataImpl();

            try {
                while (true) {
                    rpcLatency.add(ImmutableMap.of("service", "foo"), randomData.nextLong(0, 200));
                    rpcLatency.add(ImmutableMap.of("service", "bar"), (float) randomData.nextGaussian(100, 20));
                    rpcLatency.add(ImmutableMap.of("service", "zed"), (float) randomData.nextExponential(100));
                    rpcCalls.increment(ImmutableMap.of("service", "foo"));
                    rpcCalls.increment(ImmutableMap.of("service", "bar"));
                    rpcCalls.increment(ImmutableMap.of("service", "zed"));
                    Thread.sleep(1000);
                }
            } catch (final InterruptedException e) {
            }
        }
    }.start();

    try {
        server.start();
        server.join();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.indiana.d2i.sloan.internal.StopVMSimulator.java

public static void main(String[] args) {
    StopVMSimulator simulator = new StopVMSimulator();

    CommandLineParser parser = new PosixParser();

    try {/*from  w  ww .ja  v a2s. co m*/
        CommandLine line = simulator.parseCommandLine(parser, args);
        String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR));

        if (!HypervisorCmdSimulator.resourceExist(wdir)) {
            logger.error(String.format("Cannot find VM working dir: %s", wdir));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_EXIST));
        }

        Properties prop = new Properties();
        String filename = HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME;

        prop.load(new FileInputStream(new File(filename)));

        // cannot stop VM when it is not running
        VMState currentState = VMState.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE)));

        if (!currentState.equals(VMState.RUNNING)) {
            logger.error("Cannot perform stop when VM is not running");
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_RUNNING));
        }

        // stop VM
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }

        // update VM status file, i.e. set state to shutdown
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE), VMState.SHUTDOWN.toString());

        // save VM state file back
        prop.store(new FileOutputStream(new File(filename)), "");

        // success
        System.exit(0);

    } catch (ParseException e) {
        logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s",
                StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, "")));

        System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS));
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR));
    }

}

From source file:com.lxf.spider.client.ClientEvictExpiredConnections.java

public static void main(String[] args) throws Exception {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(100);//from  w  w  w.  j av  a  2s.com
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).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/", };

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

        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());
                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }
        }

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

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

    } finally {
        httpclient.close();
    }
}

From source file:au.edu.jcu.usb.USBPlotFrame.java

/**
 * Creates the XY Plot, and then listens to the USB interface (/dev/ttyUSB0) and plots the
 * read data. The USB Interface is read every second.
 *
 * @param args/*from   www  .  j  a v a2s.c o m*/
 * @throws Exception 
 */
public static void main(String args[]) throws Exception {
    USBInterface myUSB = new USBInterface("/dev/ttyUSB0");
    USBPlotFrame frame = new USBPlotFrame();
    frame.setVisible(true);
    int count = 0;

    while (true) {
        Thread.sleep(1000);
        List<Double> values = myUSB.readAsDoubleArray();

        for (Double val : values) {
            System.out.println(val.toString());
            frame.addPoint(count++, val);
        }
    }

}

From source file:barrysw19.calculon.icc.ICCInterface.java

public static void main(String[] args) throws Exception {
    if (System.getProperty("calculon.password") == null) {
        LOG.error("password must be specified.");
        System.exit(-1);/*w  w w  . j a  v  a 2 s  .c  o m*/
    }

    while (!shutdown) {
        try {
            new ICCInterface().connect();
        } catch (Exception x) {
            LOG.error("Error", x);
            try {
                Thread.sleep(60000);
            } catch (InterruptedException ix) {
                LOG.error("This doesn't happen", ix);
            }
        }
    }
}

From source file:de.hadesrofl.mqtt_client.App.java

public static void main(String[] args) {
    String cf = "";
    if (args.length > 0) {
        cf = args[0];// ww  w  . j av a2  s  . c  o  m
    } else {
        cf = "config.json";
    }
    JSONObject config = JsonReader.readFile(cf);
    if (config == null)
        System.exit(-1);
    JSONObject broker = config.getJSONObject("broker");
    JSONObject topics = broker.getJSONObject("topics");
    Database db = null;
    try {
        JSONObject database = config.getJSONObject("database");
        db = new Database(database.getString("dbHost"), database.getString("dbPort"),
                database.getString("dbName"), database.getString("dbUser"), database.getString("dbPass"));
    } catch (JSONException e) {
        System.err.println("No database mentioned in config file");
    }
    List<ClientMqtt> clients = new ArrayList<ClientMqtt>();
    List<Thread> clientThreads = new ArrayList<Thread>();
    for (String topic : topics.keySet()) {
        ClientMqtt client = null;
        if (db == null) {
            client = new ClientMqtt(broker.getString("address"), broker.getInt("port"),
                    topics.getString(topic));
        } else {
            client = new ClientMqtt(broker.getString("address"), broker.getInt("port"), topics.getString(topic),
                    db);
        }
        Thread clientThread = new Thread(client);
        client.setSubscriber(broker.getBoolean("subscribe"));
        clients.add(client);
        clientThreads.add(clientThread);
        clientThread.start();
        // Need to wait a bit as the client needs to connect first
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            System.err.println("Thread can't sleep, need to take painkillers");
        }
        client.publishMessage("Ground control to Major Tom", 1);
    }
}

From source file:com.emo.ananas.app.App.java

public static void main(String[] args) throws InterruptedException {
    final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();

    Config config = ConfigFactory.load();

    Preconditions.checkArgument(config.hasPath("emailer"), "expected an 'emailer' object in config");
    final Config emailerConfig = config.getConfig("emailer");
    Preconditions.checkArgument(emailerConfig.hasPath("smtp"), "expected emailer.smtp in config");

    EmailSenderConfig emailSenderConfig = new EmailSenderConfig(emailerConfig.getString("smtp"));

    Preconditions.checkArgument(config.hasPath("reports"), "expected reports object in config");
    final Config reportsConfig = config.getConfig("reports");
    Preconditions.checkArgument(reportsConfig.hasPath("actives"),
            "expected reports.actives with array of active declared reports in config");
    final List<String> activeReports = reportsConfig.getStringList("actives");

    final DataSourceFactory factory = new DataSourceFactory(config.getConfig("datasources"));

    for (final String activeReport : activeReports) {
        Preconditions.checkArgument(reportsConfig.hasPath(activeReport), "expected reports." + activeReport
                + " in config, because it is declared in actives report list");
    }//from  ww  w .  jav  a  2 s . c  o m

    scheduler.initialize();

    for (final String activeReport : activeReports) {
        final Config reportConfig = reportsConfig.getConfig(activeReport);
        final CronConfig cronConfig = new CronConfig(reportConfig);
        final EmailConfig emailConfig = new EmailConfig(reportConfig);
        final BaseConfig dataSource = new BaseConfig(reportConfig, factory);
        final QueryConfig queryConfig = new QueryConfig(reportConfig, dataSource.dataSource());
        final Report report = new Report(activeReport, scheduler, emailSenderConfig, emailConfig, cronConfig,
                queryConfig);
        report.schedule();
    }

    while (true) {
        Thread.sleep(60000);
    }
}

From source file:ca.uqac.info.trace.TraceGenerator.java

public static void main(String[] args) {
    // Parse command line arguments
    Options options = setupOptions();/*  w w  w  .  j  a  va 2s  .c o  m*/
    CommandLine c_line = setupCommandLine(args, options);
    int verbosity = 0, max_events = 1000000;

    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    String generator_name = "simplerandom";
    if (c_line.hasOption("g")) {
        generator_name = c_line.getOptionValue("generator");
    }
    long time_per_msg = 1000;
    if (c_line.hasOption("i")) {
        time_per_msg = Integer.parseInt(c_line.getOptionValue("i"));
    }
    if (c_line.hasOption("verbosity")) {
        verbosity = Integer.parseInt(c_line.getOptionValue("verbosity"));
    }
    if (c_line.hasOption("e")) {
        max_events = Integer.parseInt(c_line.getOptionValue("e"));
    }
    String feeder_params = "";
    if (c_line.hasOption("parameters")) {
        feeder_params = c_line.getOptionValue("parameters");
    }
    MessageFeeder mf = instantiateFeeder(generator_name, feeder_params);
    if (mf == null) {
        System.err.println("Unrecognized feeder name");
        System.exit(ERR_ARGUMENTS);
    }
    // Trap Ctrl-C to send EOT before shutting down
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            char EOT = 4;
            System.out.print(EOT);
        }
    });
    for (int num_events = 0; mf.hasNext() && num_events < max_events; num_events++) {
        long time_begin = System.nanoTime();
        String message = mf.next();
        StringBuilder out = new StringBuilder();
        out.append(message);
        System.out.print(out.toString());
        long time_end = System.nanoTime();
        long duration = time_per_msg - (long) ((time_end - time_begin) / 1000000f);
        if (duration > 0) {
            try {
                Thread.sleep(duration);
            } catch (InterruptedException e) {
            }
        }
        if (verbosity > 0) {
            System.err.print("\r" + num_events + " " + duration + "/" + time_per_msg);
        }
    }
}

From source file:net.sf.ehcache.distribution.RemoteDebugger.java

/**
 * A Remote Debugger which prints out the cache size of the monitored cache.
 * Additional logging messages can be observed by setting the logging level to debug
 * or trace for net.sf.ehcache.distribution
 *
 * @param args path_to_ehcache.xml and a cache name
 * @throws InterruptedException thrown when it is interrupted. It will keep going until then.
 *///from  www. j  a v a2  s. c  o  m
public static void main(String[] args) throws InterruptedException {

    if (args.length < 1 || args.length > 2) {
        LOG.info(
                "Command line to list caches to monitor: java -jar ehcache-remote-debugger.jar path_to_ehcache.xml\n"
                        + "Command line to monitor a specific cache: java -jar ehcache-remote-debugger.jar path_to_ehcache.xml"
                        + " cacheName");
        System.exit(2);
    }

    if (!LOG.isTraceEnabled()) {
        LOG.info("Increase the net.sf.ehcache.distribution logging level to debug or trace to see distributed"
                + " cache operations as they occur.");
    }

    CacheManager manager = new CacheManager(args[0]);
    String[] cacheNames = manager.getCacheNames();
    StringBuffer availableCaches = new StringBuffer();
    if (args.length == 1) {
        for (int i = 0; i < cacheNames.length; i++) {
            String name = cacheNames[i];
            availableCaches.append(name).append(' ');
        }
        LOG.info("Available caches are: " + availableCaches);
        System.exit(1);
    } else {
        String cacheName = args[1];
        Ehcache cache = manager.getCache(cacheName);
        if (cache == null) {
            LOG.error("No cache named " + cacheName + " exists. Available caches are: " + availableCaches);
        } else {
            LOG.info("Monitoring cache: " + cacheName);

            while (true) {
                Thread.sleep(TWO_SECONDS);
                LOG.info("Cache size: " + cache.getSize());
            }
        }
    }
}