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.fjn.helper.frameworkex.apache.commons.pool.connectionPool.ConnectionManager.java

public static void main(String[] args) {
    final ConnectionManager mgr = new ConnectionManager();
    mgr.connFactory = new ConnectionFactory();
    mgr.connFactory.setDriverClass("com.mysql.jdbc.Driver");
    mgr.connFactory.setPassword("mysql");
    mgr.connFactory.setUsername("mysql");
    mgr.connFactory.setUrl("url:localhost:3306"); // ?URL

    mgr.initConnectionPool(1000, 50, 5, 1000 * 60);
    mgr.pool = mgr.connPoolFactory.createPool();

    final AtomicInteger count = new AtomicInteger(0);

    int threadNum = Runtime.getRuntime().availableProcessors();
    ExecutorService client = Executors.newFixedThreadPool(threadNum);
    for (int i = 0; i < threadNum; i++) {
        client.submit(new Runnable() {
            @Override/*from   w  w  w.  ja  va  2 s  . c o  m*/
            public void run() {
                while (true && count.get() < 100) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                    Connection connection = null;

                    try {
                        connection = (Connection) mgr.pool.borrowObject();
                        try {

                            int value = count.incrementAndGet();
                            if (value < 100) {
                                String threadName = Thread.currentThread().getName();

                                int activeNum = mgr.pool.getNumActive();
                                int idleNum = mgr.pool.getNumIdle();
                                String content = "ThreadName: " + threadName + "\t SQL: "
                                        + "insert into tableA ( ct ) values ('" + value + "'); \t activeNum="
                                        + activeNum + "\t idleNum=" + idleNum;
                                System.out.println(content);
                            }

                        } catch (Exception e) {
                            mgr.pool.invalidateObject(connection);
                            connection = null;
                        } finally {
                            // make sure the object is returned to the pool
                            if (null != connection) {
                                mgr.pool.returnObject(connection);
                            }
                        }
                    } catch (Exception e) {
                        // failed to borrow an object
                    }

                }
            }
        });
    }
}

From source file:neembuuuploader.versioning.CheckUser.java

public static void main(String[] args) throws Exception {
    UserImpl.init(SettingsProperties.getUserId());
    for (int i = 0; i < 10000; i++) {
        getCanCustomizeNormalizing(new UserSetPriv() {

            @Override//from  w w w  . ja va  2s .com
            public void setCanCustomizeNormalizing(boolean canCustomizeNormalizing) {
                System.out.println("canCustomize = " + canCustomizeNormalizing);
            }

            @Override
            public void setNormalization(String normalization) {
                System.out.println("nomalization = " + normalization);
            }
        });
        Thread.sleep(1000);
    }
}

From source file:PinotThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    final int numQueries = QUERIES.length;
    final Random random = new Random(RANDOM_SEED);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(NUM_CLIENTS);

    for (int i = 0; i < NUM_CLIENTS; i++) {
        executorService.submit(new Runnable() {
            @Override//from w  w w .ja v a2  s  .  c  o m
            public void run() {
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost post = new HttpPost("http://localhost:8099/query");
                    CloseableHttpResponse res;
                    while (true) {
                        String query = QUERIES[random.nextInt(numQueries)];
                        post.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));
                        long start = System.currentTimeMillis();
                        res = client.execute(post);
                        res.close();
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(System.currentTimeMillis() - start);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    long startTime = System.currentTimeMillis();
    while (true) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:ee.ria.xroad.common.signature.BatchSignerIntegrationTest.java

/**
 * Main program entry point./*from  w ww. j a  va  2 s. com*/
 * @param args command-line arguments
 * @throws Exception in case of any errors
 */
public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        printUsage();

        return;
    }

    ActorSystem actorSystem = ActorSystem.create("Proxy", ConfigFactory.load().getConfig("proxy"));
    SignerClient.init(actorSystem);

    Thread.sleep(SIGNER_INIT_DELAY); // wait for signer client to connect

    BatchSigner.init(actorSystem);

    X509Certificate subjectCert = TestCertUtil.getConsumer().cert;
    X509Certificate issuerCert = TestCertUtil.getCaCert();
    X509Certificate signerCert = TestCertUtil.getOcspSigner().cert;
    PrivateKey signerKey = TestCertUtil.getOcspSigner().key;

    List<String> messages = new ArrayList<>();

    for (String arg : args) {
        messages.add(FileUtils.readFileToString(new File(arg)));
    }

    latch = new CountDownLatch(messages.size());

    Date thisUpdate = new DateTime().plusDays(1).toDate();
    final OCSPResp ocsp = OcspTestUtils.createOCSPResponse(subjectCert, issuerCert, signerCert, signerKey,
            CertificateStatus.GOOD, thisUpdate, null);

    for (final String message : messages) {
        new Thread(() -> {
            try {
                byte[] hash = hash(message);
                log.info("File: {}, hash: {}", message, hash);

                MessagePart hashPart = new MessagePart(MessageFileNames.MESSAGE, SHA512_ID,
                        calculateDigest(SHA512_ID, message.getBytes()), message.getBytes());

                List<MessagePart> hashes = Collections.singletonList(hashPart);

                SignatureBuilder builder = new SignatureBuilder();
                builder.addPart(hashPart);

                builder.setSigningCert(subjectCert);
                builder.addOcspResponses(Collections.singletonList(ocsp));

                log.info("### Calculating signature...");

                SignatureData signatureData = builder.build(
                        new SignerSigningKey(KEY_ID, CryptoUtils.CKM_RSA_PKCS_NAME), CryptoUtils.SHA512_ID);

                synchronized (sigIdx) {
                    log.info("### Created signature: {}", signatureData.getSignatureXml());

                    log.info("HashChainResult: {}", signatureData.getHashChainResult());
                    log.info("HashChain: {}", signatureData.getHashChain());

                    toFile("message-" + sigIdx + ".xml", message);

                    String sigFileName = signatureData.getHashChainResult() != null ? "batch-sig-" : "sig-";

                    toFile(sigFileName + sigIdx + ".xml", signatureData.getSignatureXml());

                    if (signatureData.getHashChainResult() != null) {
                        toFile("hash-chain-" + sigIdx + ".xml", signatureData.getHashChain());
                        toFile("hash-chain-result.xml", signatureData.getHashChainResult());
                    }

                    sigIdx++;
                }

                try {
                    verify(signatureData, hashes, message);

                    log.info("Verification successful (message hash: {})", hash);
                } catch (Exception e) {
                    log.error("Verification failed (message hash: {})", hash, e);
                }
            } catch (Exception e) {
                log.error("Error", e);
            } finally {
                latch.countDown();
            }
        }).start();
    }

    latch.await();
    actorSystem.shutdown();
}

From source file:elasticityRestinterface.RestInterfaceTester.java

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

    //           if (args.length != 1) {
    //               printUsage();
    //               
    //           }

    Logger log = Logger.getLogger(RestInterface.class);
    System.out.println("Testing Elasticity Engine Using REST interface ");
    System.out.println("One instance per 100 users expected, starting at 1");

    RestInterface resteEngine = new RestInterface("optimis-ipvm2.ds.cs.umu.se");
    String manifest = Util.getManifest("ServManifestY3.xml");
    String serviceID = "Testing";
    String sp = "optimis-spvm2.ds.cs.umu.se";
    boolean LowRiskMode;

    if ("true".equals(System.getProperty("lowrisk"))) {
        System.out.println("USING Low Risk Mode");
        LowRiskMode = true;//  w  w w.j  a  va 2s .  co  m
    } else {
        System.out.println("USING Low cost Mode");
        LowRiskMode = false;
    }
    resteEngine.startElasticity(serviceID, manifest, LowRiskMode, sp);
    resteEngine.setMode(serviceID, true);
    resteEngine.setMode(serviceID, false);
    //           System.out.println(resteEngine.getHtml());
    resteEngine.stopElasticity(serviceID);
    //Call a test-specific method which only returns when we got the -2 recommendation, and the test should then be done.
    System.out.println("\nTest done, exiting");
    Thread.sleep(500);
}

From source file:sqsAlertInbound.java

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

    // get credentials
    String user = "jreilly";
    AWSCredentials credentials = whgHelper.getCred(user);

    // use credentials to set access to SQS
    AmazonSQS sqs = whgHelper.setQueueAccess(credentials);

    // define queue that messages will be retrieved from
    String thisQueue = "alertInbound";
    String nextQueue = "alertPersist";

    while (1 > 0) {

        // pull list of current messages (up to 10) in the queue
        List<Message> messages = whgHelper.getMessagesFromQueue(thisQueue, sqs);
        System.out.println("Count of messages in " + thisQueue + ": " + messages.size());

        try {//from  w ww  .j  ava  2s .  c  om

            for (Message message : messages) {

                whgHelper.printMessage(message);
                for (Entry<String, String> entry : message.getAttributes().entrySet()) {
                    whgHelper.printMessageEntry(entry);
                }

                // validate JSON for completeness and form and handle errors
                //               if (sqs == null) {
                //                  sqs.sendMessage(new SendMessageRequest("alertErrorHandling", message.getBody()));
                //               }

                // call a function to transform message
                String alertJSON = String.valueOf(Base64.decodeBase64(message.getBody()));
                System.out.println("Transformed JSON: " + alertJSON);

                // send message to next queue
                System.out.println("Sending message to next queue.");
                sqs.sendMessage(new SendMessageRequest(nextQueue, alertJSON));

                // delete message from this queue
                System.out.println("Deleting message.\n");
                String messageRecieptHandle = message.getReceiptHandle();
                sqs.deleteMessage(new DeleteMessageRequest(thisQueue, messageRecieptHandle));

            }
            Thread.sleep(20000); // do nothing for 1000 miliseconds (1 second)

        } catch (AmazonServiceException ase) {
            whgHelper.errorMessagesAse(ase);
        } catch (AmazonClientException ace) {
            whgHelper.errorMessagesAce(ace);
        }
    }
}

From source file:cn.edu.thss.iise.bpmdemo.charts.ThermometerDemo2.java

/**
 * Starting point for the demonstration application.
 *
 * @param args//  w  w w  .j av a 2  s .  co m
 *            ignored.
 * @throws InterruptedException
 */
public static void main(final String[] args) throws InterruptedException {

    ThermometerDemo2 demo = new ThermometerDemo2("Thermometer Demo 2");
    demo.pack();
    demo.setVisible(true);

    int i = 0;
    for (i = 0; i < 10; i++) {
        Thread.sleep(1000);
        demo.dataset.setValue(new Double(new Double(10.0 * i)));
    }
}

From source file:ConsumerTool.java

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

    while (true) {
        Iterator<ConsumerTool> itr = threads.iterator();
        int running = 0;
        while (itr.hasNext()) {
            ConsumerTool 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) {
        }
    }
    Iterator<ConsumerTool> itr = threads.iterator();
    while (itr.hasNext()) {
        ConsumerTool thread = itr.next();
    }
}

From source file:com.mmj.app.common.util.PushSMSUtils.java

public static void main(String[] args) {
    for (int i = 1; i < 2; i++) {
        PushSMSUtils pushUtils = new PushSMSUtils();
        System.out.println(// ww w.j  a  va  2s .  co  m
                "?,!!!???,! " + i + ",Test Start!");

        pushUtils.sendPushMsg("??3478??", "18912386146");

        System.out.println(
                "?,!!!???,! " + i + ",Test End!");

        System.out.println("Now,start sleep!");
        try {
            Thread.sleep(1000 * 180);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Now,sleep end!");
    }
}

From source file:com.alibaba.flink.utils.MetricsMonitor.java

public static void main(String[] args) throws InterruptedException {
    if (args.length < 2) {
        System.out.println("[USAGE] MetricsMonitor <jobmanager-ip> [port] <jobid>");
        return;// w  ww.  j  av a  2s . c  o  m
    }

    ip = args[0];

    if (args.length == 3) {
        port = Utils.getInt(args[1], 8081);
        jobId = args[2];
    } else {
        jobId = args[1];
    }

    while (true) {
        System.out.println(monitorJob());
        Thread.sleep(1000 * 10);
    }
}