Example usage for java.util.concurrent TimeUnit SECONDS

List of usage examples for java.util.concurrent TimeUnit SECONDS

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit SECONDS.

Prototype

TimeUnit SECONDS

To view the source code for java.util.concurrent TimeUnit SECONDS.

Click Source Link

Document

Time unit representing one second.

Usage

From source file:Main.java

public static void main(final String[] args) throws Exception {
    Random RND = new Random();
    ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    List<Future<String>> results = new ArrayList<>(10);
    for (int i = 0; i < 10; i++) {
        results.add(es.submit(new TimeSliceTask(RND.nextInt(10), TimeUnit.SECONDS)));
    }/*  w w w  .  j  a  v a 2  s  .  c  o  m*/
    es.shutdown();
    while (!results.isEmpty()) {
        Iterator<Future<String>> i = results.iterator();
        while (i.hasNext()) {
            Future<String> f = i.next();
            if (f.isDone()) {
                System.out.println(f.get());
                i.remove();
            }
        }
    }
}

From source file:Test.java

public static void main(String[] args) throws InterruptedException {
    BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
    for (int i = 0; i < 10; i++) {
        final int localI = i;
        queue.add(new Runnable() {
            public void run() {
                doExpensiveOperation(localI);
            }/*from   w  w w .jav  a 2s .  co  m*/
        });
    }
    ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 1000, TimeUnit.MILLISECONDS, queue);
    executor.prestartAllCoreThreads();
    executor.shutdown();
    executor.awaitTermination(100000, TimeUnit.SECONDS);
}

From source file:ScheduledTask.java

public static void main(String[] args) {
    // Get an executor with 3 threads
    ScheduledExecutorService sexec = Executors.newScheduledThreadPool(3);

    ScheduledTask task1 = new ScheduledTask(1);
    ScheduledTask task2 = new ScheduledTask(2);

    // Task #1 will run after 2 seconds
    sexec.schedule(task1, 2, TimeUnit.SECONDS);

    // Task #2 runs after 5 seconds delay and keep running every 10 seconds
    sexec.scheduleAtFixedRate(task2, 5, 10, TimeUnit.SECONDS);

    try {//from  ww  w  . j  a v  a2s  .c  o  m
        TimeUnit.SECONDS.sleep(60);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    sexec.shutdown();
}

From source file:Main.java

public static void main(String[] args) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(2);
    scheduledThreadPoolExecutor.scheduleAtFixedRate(() -> {

        throw new RuntimeException(" scheduleAtFixedRate test ScheduledThreadPoolExecutor");
    }, 0, 3000, TimeUnit.MILLISECONDS);

    scheduledThreadPoolExecutor.scheduleAtFixedRate(() -> {

        System.out.println("scheduleAtFixedRate: " + LocalDateTime.now().format(formatter));
    }, 0, 2000, TimeUnit.MILLISECONDS);

    scheduledThreadPoolExecutor.schedule(() -> {

        System.out.println("schedule");
    }, 1, TimeUnit.SECONDS);
}

From source file:be.functor.cycloscan.CycloScan.java

public static void main(final String[] args) {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("context/application-context.xml");

    while (true) {
        Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
    }/* w  ww .  j av a  2s . co m*/
}

From source file:com.apress.prospringintegration.gateways.client.MainAsyncGateway.java

public static void main(String[] args) throws Exception {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("gateway-async.xml");

    TicketIssuerAsync ticketIssuerAsync = context.getBean("ticketIssueGatewayAsync", TicketIssuerAsync.class);

    Future<Ticket> result = ticketIssuerAsync.issueTicket(100L);

    Ticket ticket = result.get(1000, TimeUnit.SECONDS);
    System.out.println("Ticket: " + ticket + " was issued on: " + ticket.getIssueDateTime()
            + " with ticket id: " + ticket.getTicketId());
}

From source file:Test.java

public static void main(String args[]) throws Exception {
    ExecutorService pool = new ScheduledThreadPoolExecutor(3);
    AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(Paths.get("data.txt"),
            EnumSet.of(StandardOpenOption.READ), pool);
    CompletionHandler<Integer, ByteBuffer> handler = new CompletionHandler<Integer, ByteBuffer>() {
        public synchronized void completed(Integer result, ByteBuffer attachment) {
            for (int i = 0; i < attachment.limit(); i++) {
                System.out.print((char) attachment.get(i));
            }//  ww w . j  av a  2  s  .  c o  m
        }

        public void failed(Throwable e, ByteBuffer attachment) {
        }
    };
    final int bufferCount = 5;
    ByteBuffer buffers[] = new ByteBuffer[bufferCount];
    for (int i = 0; i < bufferCount; i++) {
        buffers[i] = ByteBuffer.allocate(10);
        fileChannel.read(buffers[i], i * 10, buffers[i], handler);
    }
    pool.awaitTermination(1, TimeUnit.SECONDS);
    for (ByteBuffer byteBuffer : buffers) {
        for (int i = 0; i < byteBuffer.limit(); i++) {
            System.out.println((char) byteBuffer.get(i));
        }
    }
}

From source file:kymr.github.io.future.LoadTest.java

public static void main(String[] args) throws InterruptedException {
    ExecutorService es = Executors.newFixedThreadPool(100);

    RestTemplate rt = new RestTemplate();
    String url = "http://localhost:8080/dr";

    StopWatch main = new StopWatch();
    main.start();//from   w  w  w.ja  v  a2  s. c  o m

    for (int i = 0; i < 100; i++) {
        es.execute(() -> {
            int idx = counter.addAndGet(1);
            log.info("Thread {}", idx);

            StopWatch sw = new StopWatch();
            sw.start();

            rt.getForObject(url, String.class);

            sw.stop();
            log.info("Elapsed: {} -> {}", idx, sw.getTotalTimeSeconds());
        });
    }

    es.shutdown();
    es.awaitTermination(100, TimeUnit.SECONDS);

    main.stop();
    log.info("Total: {}", main.getTotalTimeSeconds());
}

From source file:Test.java

public static void main(String args[]) throws Exception {
    ExecutorService pool = new ScheduledThreadPoolExecutor(3);
    AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(Paths.get("data.txt"),
            EnumSet.of(StandardOpenOption.READ), pool);
    CompletionHandler<Integer, ByteBuffer> handler = new CompletionHandler<Integer, ByteBuffer>() {
        @Override//from   w ww .  ja v a2s  .  c  o  m
        public synchronized void completed(Integer result, ByteBuffer attachment) {
            for (int i = 0; i < attachment.limit(); i++) {
                System.out.println((char) attachment.get(i));
            }
        }

        @Override
        public void failed(Throwable e, ByteBuffer attachment) {
        }
    };
    final int bufferCount = 5;
    ByteBuffer buffers[] = new ByteBuffer[bufferCount];
    for (int i = 0; i < bufferCount; i++) {
        buffers[i] = ByteBuffer.allocate(10);
        fileChannel.read(buffers[i], i * 10, buffers[i], handler);
    }
    pool.awaitTermination(1, TimeUnit.SECONDS);
    for (ByteBuffer byteBuffer : buffers) {
        for (int i = 0; i < byteBuffer.limit(); i++) {
            System.out.print((char) byteBuffer.get(i));
        }
    }
}

From source file:com.project.finalproject.Send.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    try {//from  w w  w  . j a  v  a 2 s  .c  o  m
        InputStream is = new FileInputStream("hr.json");
        String jsontxt = IOUtils.toString(is);
        JSONObject jsonObject = new JSONObject(jsontxt);
        JSONArray stream = jsonObject.getJSONArray("stream");
        for (int i = 0; i < stream.length(); i++) {
            String message = stream.getJSONObject(i).getString("value");
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
            System.out.println(" [x] Sent '" + message + "'");
            TimeUnit.SECONDS.sleep(1);
        }
    } catch (FileNotFoundException fe) {
        fe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    channel.close();
    connection.close();
}