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.boonya.http.async.examples.nio.client.AsyncClientEvictExpiredConnections.java

public static void main(String[] args) throws Exception {
    ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
    PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
    cm.setMaxTotal(100);// w  ww .  j  av a2 s. c o  m
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setConnectionManager(cm).build();
    try {
        httpclient.start();

        // 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();

        final CountDownLatch latch = new CountDownLatch(urisToGet.length);
        for (final String uri : urisToGet) {
            final HttpGet httpget = new HttpGet(uri);
            httpclient.execute(httpget, new FutureCallback<HttpResponse>() {

                @Override
                public void completed(final HttpResponse response) {
                    latch.countDown();
                    System.out.println(httpget.getRequestLine() + "->" + response.getStatusLine());
                }

                @Override
                public void failed(final Exception ex) {
                    latch.countDown();
                    System.out.println(httpget.getRequestLine() + "->" + ex);
                }

                @Override
                public void cancelled() {
                    latch.countDown();
                    System.out.println(httpget.getRequestLine() + " cancelled");
                }

            });
        }
        latch.await();

        // 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:PublisherTest.java

public static void main(String[] args) {

    Subscriber subscriber = SubscriberFactory.create(HOST, 6000, "some-subscriber");
    subscriber.subscribe(TestChannelHandler.class);
    //subscriber.subscribe(TestGsonChannelHandler.class);
    //subscriber.subscribeMulti(BackendMultiChannelHandler.class);

    /*        CountDownLatch countDownLatch = new CountDownLatch(CLIENTS);
            /*w  w w  .  j  a  v  a2 s . c  o  m*/
            for (int i = 0; i < CLIENTS; i++) {
    new Thread(() -> {
            
        Publisher publisher = PublisherFactory.create(HOST, 1337);
            
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("foo", "bar");
            
        for (int j = 0; j < MESSAGES_PER_CLIENT; j++) {
            publisher.publish("test", jsonObject);
            
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
            
        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
            
        publisher.disconnect();
            
        countDownLatch.countDown();
    }).start();
            }
            
            try {
    countDownLatch.await();
            } catch (InterruptedException e) {
    e.printStackTrace();
            }
            
            System.out.println("Test finished successfully! " + TestChannelHandler.PACKETS +  "/" + TOTAL_MESSAGES);
            
            subscriber.disconnect();*/

    Publisher publisher = PublisherFactory.create(HOST, 6000);

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("foo", "bar");
    publisher.publish("test", jsonObject);

    publisher.publishAll("test", jsonObject, new JSONObject().put("foo", "second"));

    publisher.publishAll("test", "some-subscriber", jsonObject, new JSONObject().put("foo", "second"));

    publisher.publishAll("gson", new FooBar("bar"), new FooBar("bar2"));

    publisher.publishAll("gson", "some-subscriber", new FooBar("bar"), new FooBar("bar2"));

    JSONObject backendJson = new JSONObject();
    backendJson.put("role", "update");
    backendJson.put("ping", 5);
    publisher.async().publish("backend", backendJson);

    for (int i = 0; i < 20; i++) {
        publisher.publish("test", new FooBar("bar" + i));

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    subscriber.disconnect();
    publisher.disconnect();
}

From source file:rooms.Application.java

public static void main(String[] args) throws ValueException, ThingException, InterruptedException {

    AbstractApplicationContext context = new AnnotationConfigApplicationContext(RoomConfig.class);
    //AbstractApplicationContext context = new AnnotationConfigApplicationContext(RoomConfigMongo.class);

    //        MongoOperations mo = (MongoOperations) context.getBean("mongoTemplate");
    final ThingControl tc = (ThingControl) context.getBean("thingControl");

    for (String s : context.getBeanDefinitionNames()) {
        System.out.println(s);//from w  ww . j a  v a2 s . c  o  m
    }

    System.out.println("THINGSSSS");
    for (Thing t : tc.findAllThings()) {
        System.out.println("THING: " + t);
    }

    //        mo.dropCollection(Thing.class);
    //        mo.dropCollection(Bridge.class);
    //        mo.dropCollection(Light.class);

    List<Thing> t = tc.findThingsForType("bridge");

    Bridge b = new Bridge("10.0.0.40");
    Thing tb = tc.createThing("bridge", b);

    Light l = new Light(Group.GROUP_1, "white");
    Thing tl = tc.createThing("bedroom_ceiling", l);

    Light l2 = new Light(Group.GROUP_2, "white");
    Thing tl2 = tc.createThing("bedroom_bed", l2);

    Light l3 = new Light(Group.GROUP_3, "white");
    Thing tl3 = tc.createThing("bedroom_desk", l3);

    tc.addChildThing(tb, tl);
    tc.addChildThing(tb, tl2);
    tc.addChildThing(tb, tl3);

    List<Thing<Bridge>> bridges = tc.findThingsForType(Bridge.class);

    Map<String, LightWhiteV2> lights = Maps.newHashMap();

    for (Thing<Bridge> bridgeThing : bridges) {

        Bridge bridge = tc.getValue(bridgeThing);
        LimitlessLEDControllerV2 c = new LimitlessLEDControllerV2(b.getHost(), b.getPort());

        List<Thing<Light>> lightThings = tc.getChildrenForType(Observable.just(bridgeThing), Light.class, true);
        for (Thing<Light> tempLight : lightThings) {
            Light ll = tc.getValue(tempLight);
            LightWhiteV2 white = new LightWhiteV2(tempLight.getKey(), c, ll.getLightGroup());
            lights.put(white.getName(), white);
            System.out.println("LIGHT: " + white.getName());
        }
    }

    //        lights.get("bedroom_ceiling").setOn(true);
    lights.get("bedroom_bed").setOn(true);
    Thread.sleep(2000);
    //        lights.get("bedroom_ceiling").setOn(false);
    lights.get("bedroom_bed").setOn(false);
    Thread.sleep(2000);

}

From source file:com.ikanow.infinit.e.core.CoreMain.java

/**
 * @param args//from  w  ww  . j a  v a2  s . c om
 * @throws ParseException 
 * @throws IOException 
 * @throws InterruptedException 
 */
public static void main(String[] args) throws ParseException, IOException, InterruptedException {

    CommandLineParser cliParser = new BasicParser();
    Options allOps = new Options();
    // Common
    allOps.addOption("c", "config", true, "Configuration path");
    allOps.addOption("g", "community", true, "Only run on one community");
    // Harvest specific
    allOps.addOption("h", "harvest", false, "Run harvester");
    allOps.addOption("l", "local", false, "(for debug: use dummy index)");
    allOps.addOption("i", "source", true, "(for debug: use a single source)");
    allOps.addOption("r", "reset", false, "Reset bad sources");
    // Sync specific
    allOps.addOption("s", "sync", false, "Run synchronization");
    allOps.addOption("f", "from", true, "String unix time (secs) from when to sync");
    // Custom specifc
    allOps.addOption("p", "custom", false, "Run custom processing server");
    allOps.addOption("d", "dummy", true, "Use to keep temp unwanted options on the command line");
    allOps.addOption("j", "jobtitle", true, "(for debug: run a single job)");

    CommandLine cliOpts = cliParser.parse(allOps, args);

    Globals.setIdentity(com.ikanow.infinit.e.data_model.Globals.Identity.IDENTITY_SERVICE);

    if (cliOpts.hasOption("config")) {
        String configOverride = (String) cliOpts.getOptionValue("config");
        Globals.overrideConfigLocation(configOverride);
    }
    //Set up logging
    java.io.File file = new java.io.File(
            com.ikanow.infinit.e.data_model.Globals.getLogPropertiesLocation() + ".xml");
    if (file.exists()) {
        DOMConfigurator.configure(com.ikanow.infinit.e.data_model.Globals.getLogPropertiesLocation() + ".xml");
    } else {
        PropertyConfigurator.configure(Globals.getLogPropertiesLocation());
    }

    if (cliOpts.hasOption("harvest")) {
        if (SourceUtils.checkDbSyncLock()) {
            Thread.sleep(10000); // (wait 10s and then try again)
            System.exit(0);
        }
        String communityOverride = null;
        String sourceDebug = null;
        if (cliOpts.hasOption("local")) {
            ElasticSearchManager.setLocalMode(true);
        }
        if (cliOpts.hasOption("reset")) {
            SourceUtils.resetBadSources();
        }
        if (cliOpts.hasOption("community")) {
            communityOverride = (String) cliOpts.getOptionValue("community");
        }
        if (cliOpts.hasOption("source")) {
            sourceDebug = (String) cliOpts.getOptionValue("source");
        }
        new HarvestThenProcessController()
                .startService(SourceUtils.getSourcesToWorkOn(communityOverride, sourceDebug, false, true));
    } //TESTED
    else if (cliOpts.hasOption("sync")) {
        if (SourceUtils.checkDbSyncLock()) {
            Thread.sleep(10000); // (wait 10s and then try again)
            System.exit(0);
        }
        // Sync command line options:
        long nTimeOfLastCleanse_secs = 0; // (default)
        if (cliOpts.hasOption("from")) {
            try {
                nTimeOfLastCleanse_secs = Long.parseLong((String) cliOpts.getOptionValue("from"));
            } catch (NumberFormatException e) {
                System.out.println("From date is incorrect");
                System.exit(-1);
            }
        }
        String communityOverride = null;
        String sourceDebug = null;
        if (cliOpts.hasOption("community")) {
            communityOverride = (String) cliOpts.getOptionValue("community");
        } else if (cliOpts.hasOption("source")) {
            sourceDebug = (String) cliOpts.getOptionValue("source");
        }
        SourceUtils.checkSourcesHaveHashes(communityOverride, sourceDebug);
        // (infrequently ie as part of sync, check all the sources have hashes, which the harvester depends on)

        new SynchronizationController().startService(nTimeOfLastCleanse_secs,
                SourceUtils.getSourcesToWorkOn(communityOverride, sourceDebug, true, true));
    } //TESTED
    else if (cliOpts.hasOption("custom")) {
        String jobOverride = null;
        if (cliOpts.hasOption("jobtitle")) {
            jobOverride = (String) cliOpts.getOptionValue("jobtitle");
        }
        CustomProcessingController customPxController = new CustomProcessingController();
        customPxController.checkScheduledJobs(jobOverride);
        customPxController.checkRunningJobs();
        customPxController.runThroughSavedQueues();
    } else {
        //Test code for distribution:
        //         boolean bSync = true;
        //         LinkedList<SourcePojo> testSources = null;
        //         LinkedList<SourcePojo> batchOfSources = null;
        //         testSources = getSourcesToWorkOn(null, null, bSync, true);
        //         System.out.println("Sources considered = " + testSources.size());
        //         // Grab a batch of sources
        //         batchOfSources = getDistributedSourceList(testSources, null, false);
        //         System.out.println("Sources left = " + testSources.size());
        //         System.out.println("Sources extracted = " + new com.google.gson.Gson().toJson(batchOfSources));

        System.out.println(
                "com.ikanow.infinit.e.core.server [--config <config-dir>] [--harvest [<other options>]|--sync [<other options>]|--custom [<other options>]]");
        System.exit(-1);
    }
    MongoApplicationLock.registerAppShutdown(); // (in case the saved queries are running, for some reason built in startup hook not running)
}

From source file:DruidResponseTime.java

public static void main(String[] args) throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty");
        post.addHeader("content-type", "application/json");
        CloseableHttpResponse res;/*from w  ww  . ja va  2 s  .  co m*/

        if (STORE_RESULT) {
            File dir = new File(RESULT_DIR);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }

        int length;

        // Make sure all segments online
        System.out.println("Test if number of records is " + RECORD_NUMBER);
        post.setEntity(new StringEntity("{" + "\"queryType\":\"timeseries\","
                + "\"dataSource\":\"tpch_lineitem\"," + "\"intervals\":[\"1992-01-01/1999-01-01\"],"
                + "\"granularity\":\"all\"," + "\"aggregations\":[{\"type\":\"count\",\"name\":\"count\"}]}"));
        while (true) {
            System.out.print('*');
            res = client.execute(post);
            boolean valid;
            try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent())) {
                length = in.read(BYTE_BUFFER);
                valid = new String(BYTE_BUFFER, 0, length, "UTF-8").contains("\"count\" : 6001215");
            }
            res.close();
            if (valid) {
                break;
            } else {
                Thread.sleep(5000);
            }
        }
        System.out.println("Number of Records Test Passed");

        for (int i = 0; i < QUERIES.length; i++) {
            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Start running query: " + QUERIES[i]);
            try (BufferedReader reader = new BufferedReader(
                    new FileReader(QUERY_FILE_DIR + File.separator + i + ".json"))) {
                length = reader.read(CHAR_BUFFER);
                post.setEntity(new StringEntity(new String(CHAR_BUFFER, 0, length)));
            }

            // Warm-up Rounds
            System.out.println("Run " + WARMUP_ROUND + " times to warm up cache...");
            for (int j = 0; j < WARMUP_ROUND; j++) {
                res = client.execute(post);
                res.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            int[] time = new int[TEST_ROUND];
            int totalTime = 0;
            System.out.println("Run " + TEST_ROUND + " times to get average time...");
            for (int j = 0; j < TEST_ROUND; j++) {
                long startTime = System.currentTimeMillis();
                res = client.execute(post);
                long endTime = System.currentTimeMillis();
                if (STORE_RESULT && j == 0) {
                    try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent());
                            BufferedWriter writer = new BufferedWriter(
                                    new FileWriter(RESULT_DIR + File.separator + i + ".json", false))) {
                        while ((length = in.read(BYTE_BUFFER)) > 0) {
                            writer.write(new String(BYTE_BUFFER, 0, length, "UTF-8"));
                        }
                    }
                }
                res.close();
                time[j] = (int) (endTime - startTime);
                totalTime += time[j];
                System.out.print(time[j] + "ms ");
            }
            System.out.println();

            // Process Results
            double avgTime = (double) totalTime / TEST_ROUND;
            double stdDev = 0;
            for (int temp : time) {
                stdDev += (temp - avgTime) * (temp - avgTime) / TEST_ROUND;
            }
            stdDev = Math.sqrt(stdDev);
            System.out.println("The average response time for the query is: " + avgTime + "ms");
            System.out.println("The standard deviation is: " + stdDev);
        }
    }
}

From source file:com.ict.dtube.example.operation.Producer.java

public static void main(String[] args) throws MQClientException, InterruptedException {
    CommandLine commandLine = buildCommandline(args);
    if (commandLine != null) {
        String group = commandLine.getOptionValue('g');
        String topic = commandLine.getOptionValue('t');
        String tags = commandLine.getOptionValue('a');
        String keys = commandLine.getOptionValue('k');
        String msgCount = commandLine.getOptionValue('c');

        DtubeProducer producer = new DtubeProducer(group);
        producer.setInstanceName(Long.toString(System.currentTimeMillis()));

        producer.start();//w ww .  j a  va 2 s.  co  m

        for (int i = 0; i < Integer.parseInt(msgCount); i++) {
            try {
                Message msg = new Message(//
                        topic, // topic
                        tags, // tag
                        keys, // key
                        ("Hello Dtube " + i).getBytes());// body
                SendResult sendResult = producer.send(msg);

                System.out.printf("%-8d %s\n", i, sendResult);
            } catch (Exception e) {
                e.printStackTrace();
                Thread.sleep(1000);
            }
        }

        producer.shutdown();
    }
}

From source file:com.doculibre.constellio.solr.context.SolrCoreContext.java

public static void main(String args[]) {
    HttpSolrServer server = new HttpSolrServer("http://localhost:8983/solr");
    server.setConnectionTimeout(1000);/*from w  w w .j av a  2s.c  om*/
    server.setSoTimeout(1000);
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }
    try {
        server.ping();
    } catch (SolrServerException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:uk.ac.gda.dls.client.views.RunCommandCompositeFactory.java

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

    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new BorderLayout());

    ICommandRunner iCommandRunner = new ICommandRunner() {

        @Override/*from   w  w w  .j  ava  2 s.  c  om*/
        public boolean runsource(String command, String source) {
            return false;
        }

        @Override
        public void runScript(File script, String sourceName) {
        }

        @Override
        public void runCommand(String command, String scanObserver) {
        }

        @Override
        public void runCommand(String command) {
            try {
                System.out.println(command);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        @Override
        public String locateScript(String scriptToRun) {
            return null;
        }

        @Override
        public String evaluateCommand(String command) {
            return null;
        }
    };
    final RunCommandComposite comp = new RunCommandComposite(shell, SWT.NONE, iCommandRunner, "My Label",
            "My Command", "", "Job Title", "tooltip");
    comp.setLayoutData(BorderLayout.NORTH);
    comp.setVisible(true);
    shell.pack();
    shell.setSize(400, 400);
    SWTUtils.showCenteredShell(shell);
}

From source file:com.qeekfine.PacketWithStorm.java

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

    TopologyBuilder builder = new TopologyBuilder();

    builder.setSpout("spout", new PacketSpout(), 5);

    builder.setBolt("group", new PacketGroup(), 8).shuffleGrouping("spout");
    builder.setBolt("count", new PacketSendCount(), 12).fieldsGrouping("group", new Fields("src"));

    Config conf = new Config();
    conf.setDebug(true);/* ww w.  j a va2 s. co  m*/

    if (args != null && args.length > 0) {
        conf.setNumWorkers(3);

        StormSubmitter.submitTopologyWithProgressBar(args[0], conf, builder.createTopology());
    } else {
        conf.setMaxTaskParallelism(3);

        LocalCluster cluster = new LocalCluster();
        cluster.submitTopology("word-count", conf, builder.createTopology());

        Thread.sleep(10000);

        cluster.shutdown();
    }
}

From source file:com.alibaba.rocketmq.example.operation.Producer.java

public static void main(String[] args) throws MQClientException, InterruptedException {
    CommandLine commandLine = buildCommandline(args);
    if (commandLine != null) {
        String group = commandLine.getOptionValue('g');
        String topic = commandLine.getOptionValue('t');
        String tags = commandLine.getOptionValue('a');
        String keys = commandLine.getOptionValue('k');
        String msgCount = commandLine.getOptionValue('c');

        DefaultMQProducer producer = new DefaultMQProducer(group);
        producer.setInstanceName(Long.toString(System.currentTimeMillis()));

        producer.start();// www.  java 2  s  .  c om

        for (int i = 0; i < Integer.parseInt(msgCount); i++) {
            try {
                Message msg = new Message(//
                        topic, // topic
                        tags, // tag
                        keys, // key
                        ("Hello RocketMQ " + i).getBytes());// body
                SendResult sendResult = producer.send(msg);

                System.out.printf("%-8d %s\n", i, sendResult);
            } catch (Exception e) {
                e.printStackTrace();
                Thread.sleep(1000);
            }
        }

        producer.shutdown();
    }
}