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:fresto.datastore.titan.TitanEventWriter.java

public static void main(String[] args) throws Exception {
    if (args.length < 4) {
        LOGGER.error(/*from  www  . ja v a2s  .  c om*/
                "Argumests needed : <streamer url> <storage backend> <storage hostname> <max commit count>");
        System.exit(1);
    } else {
        STREAMER_URL = args[0];
        STORAGE_BACKEND = args[1];
        STORAGE_HOSTNAME = args[2];
        try {
            MAX_COMMIT_COUNT = Integer.parseInt(args[3]);
        } catch (NumberFormatException e) {
            LOGGER.error("Commit count should be an integer");
        }
    }

    final ZMQ.Context context = ZMQ.context(1);

    final FrestoEventQueue frestoEventQueue = new FrestoEventQueue();

    final Thread queueMonitorThread = new Thread() {
        //Logger _LOGGER = Logger.getLogger("writerThread");
        @Override
        public void run() {
            while (work) {
                try {
                    LOGGER.info("frestoEventQueue size = " + frestoEventQueue.size());
                    Thread.sleep(1000);
                } catch (InterruptedException ie) {
                }

            }
        }
    };

    final Thread writerThread = new Thread() {
        //Logger _LOGGER = Logger.getLogger("writerThread");
        @Override
        public void run() {
            //StopWatch _watch = new JavaLogStopWatch(_LOGGER);
            FrestoStopWatch _watch = new FrestoStopWatch();
            FrestoStopWatch _durationWatch = new FrestoStopWatch();

            TitanEventWriter eventWriter = new TitanEventWriter();

            // Open database
            eventWriter.openTitanGraph();

            ZMQ.Socket puller = context.socket(ZMQ.PULL);
            //puller.connect("tcp://" + frontHost + ":" + frontPort);
            puller.connect(STREAMER_URL);

            //Consume socket data
            frestoEventQueue.setPullerSocket(puller);
            frestoEventQueue.start();

            int nextCommitCount = 0;
            int count = 0;
            long elapsedTime = 0;
            long duration = 0;

            _durationWatch.start();

            while (work) {

                // To wait until at least one event in queue
                if (frestoEventQueue.isEmpty()) {
                    try {
                        Thread.sleep(SLEEP_TIME);
                        continue;
                    } catch (InterruptedException ie) {
                    }
                }

                nextCommitCount = frestoEventQueue.size();

                for (int i = 0; i < nextCommitCount; i++) {
                    _watch.start();
                    count++;

                    FrestoEvent frestoEvent = frestoEventQueue.poll();

                    try {
                        eventWriter.writeEventData(frestoEvent.topic, frestoEvent.eventBytes);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        //
                    }

                    elapsedTime += _watch.stop();
                    duration += _durationWatch.stop();

                    if (count == MAX_COMMIT_COUNT) {
                        eventWriter.commitGraph();
                        LOGGER.info(count + " events processed for " + elapsedTime + " ms. (total time "
                                + duration + " ms.) Remaining events " + frestoEventQueue.size());

                        count = 0;
                        elapsedTime = 0;
                        duration = 0;
                        // Stop FOR clause
                    }
                }

                eventWriter.commitGraph();

                LOGGER.info(count + " events processed for " + elapsedTime + " ms. (total time " + duration
                        + " ms.) Remaining events " + frestoEventQueue.size());

                count = 0;
                elapsedTime = 0;
                duration = 0;
            }
            LOGGER.info("Shutting down...");

            if (g.isOpen()) {
                g.commit();
                g.shutdown();
            }

            puller.close();
            context.term();

            LOGGER.info("Good bye.");
        }
    };

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            System.out.println("Interrupt received, killing server");
            // To break while clause
            frestoEventQueue.stopWork();
            work = false;

            try {
                writerThread.join();
                frestoEventQueue.join();
                //queueMonitorThread.join();

            } catch (InterruptedException e) {
            }
        }
    });

    //queueMonitorThread.start();
    writerThread.start();

}

From source file:com.amazonaws.services.kinesis.application.stocktrades.writer.StockTradesWriter.java

public static void main(String[] args) throws Exception {
    checkUsage(args);//from  ww w . j  av a  2  s. c o m

    String streamName = args[0];
    String regionName = args[1];
    Region region = RegionUtils.getRegion(regionName);
    if (region == null) {
        System.err.println(regionName + " is not a valid AWS region.");
        System.exit(1);
    }

    AWSCredentials credentials = CredentialUtils.getCredentialsProvider().getCredentials();

    AmazonKinesis kinesisClient = new AmazonKinesisClient(credentials,
            ConfigurationUtils.getClientConfigWithUserAgent());
    kinesisClient.setRegion(region);

    // Validate that the stream exists and is active
    validateStream(kinesisClient, streamName);

    // Repeatedly send stock trades with a 100 milliseconds wait in between
    StockTradeGenerator stockTradeGenerator = new StockTradeGenerator();
    while (true) {
        StockTrade trade = stockTradeGenerator.getRandomTrade();
        sendStockTrade(trade, kinesisClient, streamName);
        Thread.sleep(100);
    }
}

From source file:eu.learnpad.simulator.mon.MyGlimpseProbe_SimMonLearnPAd.java

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

    MyGlimpseProbe_SimMonLearnPAd aGenericProbe = new MyGlimpseProbe_SimMonLearnPAd(
            Manager.createProbeSettingsPropertiesObject(
                    "org.apache.activemq.jndi.ActiveMQInitialContextFactory", "tcp://localhost:61616", "system",
                    "manager", "TopicCF", "jms.probeTopic", false, "probeName", "probeTopic"));

    DebugMessages.println(TimeStamp.getCurrentTime(), MyGlimpseProbe_SimMonLearnPAd.class.getName(),
            "Sending a set of events:\nsimstart, processstart, taskstart, taskfailed, taskstart, taskend, processend, sessionscoreupdate, simendinfinite");
    try {//from  w ww.j av  a2s  .  com
        AbstractEvent event;
        event = new SimulationStartEvent();
        aGenericProbe.generateAndSendExample_GlimpseBaseEvents_StringPayload("SIMULATION_START", event);

        Thread.sleep(2000);

        event = new ProcessStartEvent();
        aGenericProbe.generateAndSendExample_GlimpseBaseEvents_StringPayload("PROCESS_START", event);

        Thread.sleep(2000);

        event = new TaskStartEvent();
        aGenericProbe.generateAndSendExample_GlimpseBaseEvents_StringPayload("TASK_START", event);

        Thread.sleep(2000);

        event = new TaskFailedEvent();
        aGenericProbe.generateAndSendExample_GlimpseBaseEvents_StringPayload("TASK_FAILED", event);

        Thread.sleep(2000);

        event = new TaskStartEvent();
        aGenericProbe.generateAndSendExample_GlimpseBaseEvents_StringPayload("TASK_START", event);

        Thread.sleep(2000);

        event = new TaskEndEvent();
        aGenericProbe.generateAndSendExample_GlimpseBaseEvents_StringPayload("TASK_END", event);

        Thread.sleep(2000);

        event = new ProcessEndEvent();
        aGenericProbe.generateAndSendExample_GlimpseBaseEvents_StringPayload("PROCESS_END", event);

        Thread.sleep(2000);

        event = new SessionScoreUpdateEvent();
        aGenericProbe.generateAndSendExample_GlimpseBaseEvents_StringPayload("SESSION_SCORE_UPDATE", event);

        Thread.sleep(2000);

        event = new SimulationEndEvent();
        aGenericProbe.generateAndSendExample_GlimpseBaseEvents_StringPayload("SIMULATION_END", event);

    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:io.alicorn.device.client.DeviceClient.java

public static void main(String[] args) {
    logger.info("Starting Alicorn Client System");

    // Prepare Display Color.
    transform3xWrite(DisplayTools.commandForColor(0, 204, 255));

    // Setup text information.
    //        transform3xWrite(DisplayTools.commandForText("Sup Fam"));

    class StringWrapper {
        public String string = "";
    }/*from w  ww  . java2 s .  c  om*/
    final StringWrapper string = new StringWrapper();

    // Text Handler.
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            String latestString = "";
            String outputStringLine1Complete = "";
            long outputStringLine1Cursor = 1;
            int outputStringLine1Mask = 0;
            String outputStringLine2 = "";

            while (true) {
                if (!latestString.equals(string.string)) {
                    latestString = string.string;
                    String[] latestStrings = latestString.split("::");
                    outputStringLine1Complete = latestStrings[0];
                    outputStringLine1Mask = outputStringLine1Complete.length();
                    outputStringLine1Cursor = 0;

                    // Trim second line to a length of sixteen.
                    outputStringLine2 = latestStrings.length > 1 ? latestStrings[1] : "";
                    if (outputStringLine2.length() > 16) {
                        outputStringLine2 = outputStringLine2.substring(0, 16);
                    }
                }

                StringBuilder outputStringLine1 = new StringBuilder();
                if (outputStringLine1Complete.length() > 0) {
                    long cursor = outputStringLine1Cursor;
                    for (int i = 0; i < 16; i++) {
                        outputStringLine1.append(
                                outputStringLine1Complete.charAt((int) (cursor % outputStringLine1Mask)));
                        cursor += 1;
                    }
                    outputStringLine1Cursor += 1;
                } else {
                    outputStringLine1.append("                ");
                }

                try {
                    transform3xWrite(
                            DisplayTools.commandForText(outputStringLine1.toString() + outputStringLine2));
                    Thread.sleep(400);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });
    thread.start();

    // Event Handler
    while (true) {
        try {
            String url = "http://169.254.90.174:9789/api/iot/narwhalText";
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            string.string = apacheHttpEntityToString(response.getEntity());

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

From source file:com.easarrive.aws.plugins.common.service.impl.SimpleProducerConsumer.java

public static void main(String[] args) throws InterruptedException {
    final AWSCredentials credentials = new BasicAWSCredentials("AKIAIDPJMKK4UHLE3OVA",
            "A+cn+TT3tUs6xbto5k1IKkWwPLBq995aOkqKxZNY");

    final String endpoint = "sqs.us-west-2.amazonaws.com";
    final String queueName = "image";
    final int producerCount = 10;
    final int consumerCount = 3;
    final int batchSize = 3;
    final int messageSizeByte = 10000;
    final int runTimeMinutes = 100;

    // 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 ww. ja va2 s .c  o 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++) {
        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++) {
        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:cz.muni.fi.xklinec.zipstream.App.java

/**
 * Entry point. /* w w w  .j av  a2  s  .  co  m*/
 * 
 * @param args
 * @throws FileNotFoundException
 * @throws IOException
 * @throws NoSuchFieldException
 * @throws ClassNotFoundException
 * @throws NoSuchMethodException 
 */
public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchFieldException,
        ClassNotFoundException, NoSuchMethodException, InterruptedException {
    OutputStream fos = null;
    InputStream fis = null;

    if ((args.length != 0 && args.length != 2)) {
        System.err.println(String.format("Usage: app.jar source.apk dest.apk"));
        return;
    } else if (args.length == 2) {
        System.err.println(
                String.format("Will use file [%s] as input file and [%s] as output file", args[0], args[1]));
        fis = new FileInputStream(args[0]);
        fos = new FileOutputStream(args[1]);
    } else if (args.length == 0) {
        System.err.println(String.format("Will use file [STDIN] as input file and [STDOUT] as output file"));
        fis = System.in;
        fos = System.out;
    }

    final Deflater def = new Deflater(9, true);
    ZipArchiveInputStream zip = new ZipArchiveInputStream(fis);

    // List of postponed entries for further "processing".
    List<PostponedEntry> peList = new ArrayList<PostponedEntry>(6);

    // Output stream
    ZipArchiveOutputStream zop = new ZipArchiveOutputStream(fos);
    zop.setLevel(9);

    // Read the archive
    ZipArchiveEntry ze = zip.getNextZipEntry();
    while (ze != null) {

        ZipExtraField[] extra = ze.getExtraFields(true);
        byte[] lextra = ze.getLocalFileDataExtra();
        UnparseableExtraFieldData uextra = ze.getUnparseableExtraFieldData();
        byte[] uextrab = uextra != null ? uextra.getLocalFileDataData() : null;

        // ZipArchiveOutputStream.DEFLATED
        // 

        // Data for entry
        byte[] byteData = Utils.readAll(zip);
        byte[] deflData = new byte[0];
        int infl = byteData.length;
        int defl = 0;

        // If method is deflated, get the raw data (compress again).
        if (ze.getMethod() == ZipArchiveOutputStream.DEFLATED) {
            def.reset();
            def.setInput(byteData);
            def.finish();

            byte[] deflDataTmp = new byte[byteData.length * 2];
            defl = def.deflate(deflDataTmp);

            deflData = new byte[defl];
            System.arraycopy(deflDataTmp, 0, deflData, 0, defl);
        }

        System.err.println(String.format(
                "ZipEntry: meth=%d " + "size=%010d isDir=%5s " + "compressed=%07d extra=%d lextra=%d uextra=%d "
                        + "comment=[%s] " + "dataDesc=%s " + "UTF8=%s " + "infl=%07d defl=%07d " + "name [%s]",
                ze.getMethod(), ze.getSize(), ze.isDirectory(), ze.getCompressedSize(),
                extra != null ? extra.length : -1, lextra != null ? lextra.length : -1,
                uextrab != null ? uextrab.length : -1, ze.getComment(),
                ze.getGeneralPurposeBit().usesDataDescriptor(), ze.getGeneralPurposeBit().usesUTF8ForNames(),
                infl, defl, ze.getName()));

        final String curName = ze.getName();

        // META-INF files should be always on the end of the archive, 
        // thus add postponed files right before them
        if (curName.startsWith("META-INF") && peList.size() > 0) {
            System.err.println(
                    "Now is the time to put things back, but at first, I'll perform some \"facelifting\"...");

            // Simulate som evil being done
            Thread.sleep(5000);

            System.err.println("OK its done, let's do this.");
            for (PostponedEntry pe : peList) {
                System.err.println(
                        "Adding postponed entry at the end of the archive! deflSize=" + pe.deflData.length
                                + "; inflSize=" + pe.byteData.length + "; meth: " + pe.ze.getMethod());

                pe.dump(zop, false);
            }

            peList.clear();
        }

        // Capturing interesting files for us and store for later.
        // If the file is not interesting, send directly to the stream.
        if ("classes.dex".equalsIgnoreCase(curName) || "AndroidManifest.xml".equalsIgnoreCase(curName)) {
            System.err.println("### Interesting file, postpone sending!!!");

            PostponedEntry pe = new PostponedEntry(ze, byteData, deflData);
            peList.add(pe);
        } else {
            // Write ZIP entry to the archive
            zop.putArchiveEntry(ze);
            // Add file data to the stream
            zop.write(byteData, 0, infl);
            zop.closeArchiveEntry();
        }

        ze = zip.getNextZipEntry();
    }

    // Cleaning up stuff
    zip.close();
    fis.close();

    zop.finish();
    zop.close();
    fos.close();

    System.err.println("THE END!");
}

From source file:com.couragelabs.logging.GlobalContextSocketAppender.java

/**
 * Use this method to test the log appender. First, run the VerySimpleLogger.
 *
 * @param args Program arguments. None are needed.
 * @throws java.lang.Exception if things go wrong
 *///from  w w w  .  java 2  s . co m
public static void main(String[] args) throws Exception {
    Logger logger = Logger.getLogger(GlobalContextSocketAppender.class);
    logger.info("here you go");
    logger.debug("this is fun");

    System.out.println("Sleeping...");
    Thread.sleep(5000);
    System.out.println("Exiting...");
    System.exit(0);
}

From source file:com.xlson.standalonewar.Starter.java

/**
 * @param args the command line arguments
 *//*from w ww.  jav  a  2  s . c  om*/
public static void main(String[] args) {
    try {
        defaultProperties = new PropertiesConfiguration(
                Starter.class.getClassLoader().getResource("webserver.properties").toURI().toURL());

        appendClasspath(defaultProperties.getList("webserver.extraClasspath"));

        config = loadConfig();

        final String PROP_NAME_WEBSERVER_TIMEOUT = defaultProperties.getString("PROP_NAME_WEBSERVER_TIMEOUT",
                "webserver.timeout");
        int timeout = Integer.parseInt(getString(PROP_NAME_WEBSERVER_TIMEOUT, "0"));
        start();
        if (timeout != 0) {
            Thread.sleep(timeout);
            stop();
        }
    } catch (Exception ex) {
        logger.error("error", ex);
        System.err.println(ex.getMessage());
        System.exit(-1);
    }
}

From source file:AmazonKinesisCreate.java

public static void main(String[] args) throws Exception {
    init();/*from  w  ww.  j a  v a 2s .  c  om*/

    final String myStreamName = "philsteststream";
    final Integer myStreamSize = 1;

    // Create a stream. The number of shards determines the provisioned throughput.

    CreateStreamRequest createStreamRequest = new CreateStreamRequest();
    createStreamRequest.setStreamName(myStreamName);
    createStreamRequest.setShardCount(myStreamSize);

    // pt
    kinesisClient.createStream(createStreamRequest);

    // The stream is now being created.
    LOG.info("Creating Stream : " + myStreamName);
    waitForStreamToBecomeAvailable(myStreamName);

    // list all of my streams
    ListStreamsRequest listStreamsRequest = new ListStreamsRequest();
    listStreamsRequest.setLimit(10);
    ListStreamsResult listStreamsResult = kinesisClient.listStreams(listStreamsRequest);
    List<String> streamNames = listStreamsResult.getStreamNames();
    while (listStreamsResult.isHasMoreStreams()) {
        if (streamNames.size() > 0) {
            listStreamsRequest.setExclusiveStartStreamName(streamNames.get(streamNames.size() - 1));
        }

        listStreamsResult = kinesisClient.listStreams(listStreamsRequest);
        streamNames.addAll(listStreamsResult.getStreamNames());

    }
    LOG.info("Printing my list of streams : ");

    // print all of my streams.
    if (!streamNames.isEmpty()) {
        System.out.println("List of my streams: ");
    }
    for (int i = 0; i < streamNames.size(); i++) {
        System.out.println(streamNames.get(i));
    }

    LOG.info("Putting records in stream : " + myStreamName);
    // Write 10 records to the stream
    for (int j = 0; j < 10; j++) {

        try {
            PutRecordRequest putRecordRequest = new PutRecordRequest();
            putRecordRequest.setStreamName(myStreamName);
            putRecordRequest.setData(ByteBuffer.wrap(String.format("testData-%d", j).getBytes()));
            putRecordRequest.setPartitionKey(String.format("partitionKey-%d", j));
            PutRecordResult putRecordResult = kinesisClient.putRecord(putRecordRequest);
            System.out.println("Successfully putrecord, partition key : " + putRecordRequest.getPartitionKey()
                    + ", ShardID : " + putRecordResult.getShardId());
            Thread.sleep(1000);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // Delete the stream.

    /*
    LOG.info("Deleting stream : " + myStreamName);
    DeleteStreamRequest deleteStreamRequest = new DeleteStreamRequest();
    deleteStreamRequest.setStreamName(myStreamName);
            
    kinesisClient.deleteStream(deleteStreamRequest);
    // The stream is now being deleted.
    LOG.info("Stream is now being deleted : " + myStreamName);
            
    LOG.info("Streaming completed" + myStreamName);
    */

}

From source file:co.mitro.core.util.RPCLogReplayer.java

public static void main(String[] args) throws IOException, InterruptedException, KeyManagementException,
        UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {

    List<Request> requests = new ArrayList<>();
    ExecutorService executor = Executors.newFixedThreadPool(5);
    for (int i = 0; i < args.length; ++i) {
        String filename = args[i];
        System.err.println("Reading file: " + filename);
        JsonRecordReader rr = JsonRecordReader.MakeFromFilename(filename);
        JsonRecordReader.JsonLog log;// w  w  w . ja v a2s  . c o  m
        try {
            while (null != (log = rr.readJson())) {
                if (Strings.isNullOrEmpty(log.payload.transactionId) && !log.payload.implicitBeginTransaction) {
                    // read only transaction
                    requests.add(new Request(log.metadata.endpoint, log.payload));
                }
            }
        } catch (EOFException e) {
            System.err.println("unexpected end of file; skipping");
        }
    }

    // run the simulation for a while.
    long scaling = 1000;
    double requestsPerMs = 353. / 9805199;
    long START_MS = 0;
    // run for 20 min
    long END_MS = 20 * 60 * 1000;
    long now = START_MS;
    int count = 0;
    while (now < END_MS) {
        double toSleep = nextExp(requestsPerMs * scaling);
        now += toSleep;
        ++count;
        Thread.sleep((long) toSleep);
        executor.execute(new SendQuery(requests.get(RNG.nextInt(requests.size()))));
        System.out.println("count: " + count + "\t time:" + now + "\t rate:" + (double) count / now);
    }
    executor.awaitTermination(1, TimeUnit.MINUTES);

}