Example usage for java.util.concurrent ThreadPoolExecutor execute

List of usage examples for java.util.concurrent ThreadPoolExecutor execute

Introduction

In this page you can find the example usage for java.util.concurrent ThreadPoolExecutor execute.

Prototype

public void execute(Runnable command) 

Source Link

Document

Executes the given task sometime in the future.

Usage

From source file:MainClass.java

public static void main(String[] args) {
    int nTasks = 5;
    long n = 1000L;
    int tpSize = 10;

    ThreadPoolExecutor tpe = new ThreadPoolExecutor(tpSize, tpSize, 50000L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());

    Task[] tasks = new Task[nTasks];
    for (int i = 0; i < nTasks; i++) {
        tasks[i] = new Task(n, "Task " + i);
        tpe.execute(tasks[i]);
    }/* ww  w  .ja v  a 2s.c o  m*/
    tpe.shutdown();
}

From source file:com.guns.media.tools.yuv.MediaTool.java

/**
 * @param args the command line arguments
 *///from www  . j  a  va 2 s  . c o  m
public static void main(String[] args) throws IOException {

    try {
        Options options = getOptions();
        CommandLine cmd = null;
        int offset = 0;
        CommandLineParser parser = new GnuParser();
        cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            printHelp(options);
            exit(1);
        }

        if (cmd.hasOption("offset")) {
            offset = new Integer(cmd.getOptionValue("offset"));
        }
        int frame = new Integer(cmd.getOptionValue("f"));

        //  int scale = new Integer(args[2]);
        BufferedInputStream if1 = new BufferedInputStream(new FileInputStream(cmd.getOptionValue("if1")));
        BufferedInputStream if2 = new BufferedInputStream(new FileInputStream(cmd.getOptionValue("if2")));

        DataStorage.create(new Integer(cmd.getOptionValue("f")));

        int width = new Integer(cmd.getOptionValue("w"));
        int height = new Integer(cmd.getOptionValue("h"));
        LookUp.initSSYUV(width, height);
        //  int[][] frame1 = new int[width][height];
        //  int[][] frame2 = new int[width][height];
        int nRead;
        int fRead;
        byte[] data = new byte[width * height + ((width * height) / 2)];
        byte[] data1 = new byte[width * height + ((width * height) / 2)];
        int frames = 0;
        long start_ms = System.currentTimeMillis() / 1000L;
        long end_ms = start_ms;

        if (offset > 0) {
            if1.skip(((width * height + ((width * height) / 2)) * offset));
        } else if (offset < 0) {
            if2.skip(((width * height + ((width * height) / 2)) * (-1 * offset)));
        }

        if (cmd.hasOption("psnr")) {
            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1) && frames < frame) {
                byte[] data_out = data.clone();
                byte[] data1_out = data1.clone();

                PSNRCalculatorThread wt = new PSNRCalculatorThread(data_out, data1_out, frames, width, height);
                executor.execute(wt);
                frames++;

            }
            executor.shutdown();
            end_ms = System.currentTimeMillis();

            System.out.println("Frame Rate :" + frames * 1000 / ((end_ms - start_ms)));
            for (int i = 0; i < frames; i++) {
                System.out.println(
                        i + "," + 10 * Math.log10((255 * 255) / (DataStorage.getFrame(i) / (width * height))));

            }
        }
        if (cmd.hasOption("sub")) {

            RandomAccessFile raf = new RandomAccessFile(cmd.getOptionValue("o"), "rw");

            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1)) {
                byte[] data_out = data.clone();
                byte[] data1_out = data1.clone();

                ImageSubstractThread wt = new ImageSubstractThread(data_out, data1_out, frames, width, height,
                        raf);
                //wt.run();
                executor.execute(wt);

                frames++;

            }
            executor.shutdown();
            end_ms = System.currentTimeMillis() / 1000L;
            System.out.println("Frame Rate :" + frames / ((end_ms - start_ms)));

            raf.close();
        }
        if (cmd.hasOption("ss") && !cmd.getOptionValue("o").matches("-")) {

            RandomAccessFile raf = new RandomAccessFile(cmd.getOptionValue("o"), "rw");

            // RandomAccessFile ra =  new RandomAccessFile(cmd.getOptionValue("o"), "rw");
            // MappedByteBuffer raf = new RandomAccessFile(cmd.getOptionValue("o"), "rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, ((width*height)+(width*height/2))*frame);
            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1) && frames < frame) {
                byte[] data_out = data.clone();
                byte[] data1_out = data1.clone();

                SidebySideImageThread wt = new SidebySideImageThread(data_out, data1_out, frames, width, height,
                        raf);
                // MPSidebySideImageThread wt = new MPSidebySideImageThread(data_out, data1_out, frames, width, height, ra);
                frames++;
                // wt.run();

                executor.execute(wt);
            }
            executor.shutdown();
            end_ms = System.currentTimeMillis() / 1000L;

            while (!executor.isTerminated()) {

            }

            raf.close();
        }
        if (cmd.hasOption("ss") && cmd.getOptionValue("o").matches("-")) {

            PrintStream stdout = new PrintStream(System.out);

            // RandomAccessFile ra =  new RandomAccessFile(cmd.getOptionValue("o"), "rw");
            // MappedByteBuffer raf = new RandomAccessFile(cmd.getOptionValue("o"), "rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, ((width*height)+(width*height/2))*frame);
            // ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1) && frames < frame) {
                byte[] data_out = data.clone();
                byte[] data1_out = data1.clone();

                SidebySideImageThread wt = new SidebySideImageThread(data_out, data1_out, frames, width, height,
                        stdout);
                // MPSidebySideImageThread wt = new MPSidebySideImageThread(data_out, data1_out, frames, width, height, ra);
                frames++;
                // wt.run();

                wt.run();
            }

            end_ms = System.currentTimeMillis() / 1000L;
            System.out.println("Frame Rate :" + frames / ((end_ms - start_ms)));

            stdout.close();
        }
        if (cmd.hasOption("image")) {

            System.setProperty("java.awt.headless", "true");
            //ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1)) {

                if (frames == frame) {
                    byte[] data_out = data.clone();
                    byte[] data1_out = data1.clone();

                    Frame f1 = new Frame(data_out, width, height, Frame.YUV420);
                    Frame f2 = new Frame(data1_out, width, height, Frame.YUV420);
                    //       System.out.println(cmd.getOptionValue("o"));
                    ExtractImageThread wt = new ExtractImageThread(f1, frames,
                            cmd.getOptionValue("if1") + "frame1-" + cmd.getOptionValue("o"));
                    ExtractImageThread wt1 = new ExtractImageThread(f2, frames,
                            cmd.getOptionValue("if2") + "frame2-" + cmd.getOptionValue("o"));
                    //   executor.execute(wt);
                    executor.execute(wt);
                    executor.execute(wt1);
                }
                frames++;

            }
            executor.shutdown();
            //  executor.shutdown();
            end_ms = System.currentTimeMillis() / 1000L;
            System.out.println("Frame Rate :" + frames / ((end_ms - start_ms)));
        }

    } catch (ParseException ex) {
        Logger.getLogger(MediaTool.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:CreateTest.java

static void doTestPool(int nThreads) {
    done = false;// w  w w . j a  va  2 s  .c  o m
    nCalls = new AtomicInteger(0);
    ThreadPoolExecutor tpe = new ThreadPoolExecutor(nThreads, nThreads, 50000L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());
    Runnable r = new CreateTest();
    for (int i = 0; i < target; i++) {
        tpe.execute(r);
    }
    tpe.shutdown();
    try {
        tpe.awaitTermination(10000000L, TimeUnit.SECONDS);
    } catch (Exception e) {
    }
}

From source file:com.l2jfree.util.concurrent.L2ThreadPool.java

public static void execute(Runnable r) {
    r = ExecuteWrapper.wrap(r);/*from  w w  w  .  j av a 2  s.c  om*/

    final ThreadPoolExecutor tpe = getRandomPool(_instantPools);
    tpe.execute(r);
}

From source file:com.l2jfree.util.concurrent.L2ThreadPool.java

public static void executeLongRunning(Runnable r) {
    r = ExecuteWrapper.wrapLongRunning(r);

    final ThreadPoolExecutor tpe = getRandomPool(_longRunningPools);
    tpe.execute(r);
}

From source file:com.clustercontrol.plugin.impl.AsyncWorkerPlugin.java

public static void commitTaskExecution(AsyncTask task) {
    ThreadPoolExecutor executor = _executorMap.get(task._worker);

    synchronized (_executorLock.get(task._worker)) {
        executor.execute(task);
    }/*w ww.j  av a 2s.  c  o m*/

    if (log.isDebugEnabled()) {
        log.debug("committed, task will be executed. (worker = " + task._worker + ", taskId = " + task._taskId
                + ", param = " + task._param + ")");
    }
}

From source file:Main.java

public static void blockUntilConnected(final SocketChannel channel, long timeout) throws IOException {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, timeout, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());
    FutureTask<Boolean> future = new FutureTask<Boolean>(new Callable<Boolean>() {
        public Boolean call() {
            while (!channel.isConnected()) {
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                }/*  w ww.j a v a2s .  co m*/
            }
            return true;
        }
    });
    executor.execute(future);

    try {
        future.get(timeout, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        channel.close();
        throw new IOException(e);
    }
}

From source file:com.dumontierlab.pdb2rdf.Pdb2Rdf.java

private static ExecutorService getThreadPool(CommandLine cmd) {
    // twice the number of PU
    final Object monitor = new Object();
    int numberOfThreads = getNumberOfThreads(cmd);
    LOG.info("Using " + numberOfThreads + " threads.");
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(numberOfThreads, numberOfThreads, 10,
            TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(1), new RejectedExecutionHandler() {
                @Override//from w w  w .j  a  v  a2  s. co m
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    synchronized (monitor) {
                        try {
                            monitor.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                    executor.execute(r);
                }
            }) {
        @Override
        protected void afterExecute(Runnable r, Throwable t) {
            synchronized (monitor) {
                monitor.notify();
            }
            super.afterExecute(r, t);
        }
    };

    return threadPool;
}

From source file:Main.java

public void runTest() throws Exception {
    ThreadPoolExecutor tp = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>());
    tp.setRejectedExecutionHandler(// w  ww  .  java  2 s .  com
            (Runnable r, ThreadPoolExecutor executor) -> System.out.println("Task rejected: " + r));
    Semaphore oneTaskDone = new Semaphore(0);
    tp.execute(() -> {
        System.out.println("Sleeping");
        try {
            Thread.sleep(300);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Done sleeping");
        oneTaskDone.release();
    });
    tp.execute(new Runnable() {
        @Override
        public void run() {
            System.out.println("Never happends");
        }

        @Override
        public String toString() {
            return "Rejected Runnable";
        }
    });
    oneTaskDone.acquire();
    tp.execute(() -> System.out.println("Running"));
    tp.shutdown();
    tp.awaitTermination(100, TimeUnit.MILLISECONDS);
    System.out.println("Finished");
}

From source file:com.cloudhopper.commons.io.demo.FileServerMain.java

public static void loadFilesFromDir(String dir, int threads) {
    ThreadPoolExecutor ex = new ThreadPoolExecutor(threads, threads, 5000l, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());
    ex.prestartAllCoreThreads();/*from w ww. j av a2  s  . co  m*/

    IdGenerator idGen = new UUIDIdGenerator();
    final FileStore store = new SimpleNIOFileStore(idGen, "/tmp/fileStore/");

    final long start = System.currentTimeMillis();
    int count = 0;

    Iterator<File> it = FileUtils.iterateFiles(new File(dir), null, true);
    while (it.hasNext()) {
        final File f = it.next();
        final int num = count++;
        Runnable job = new Runnable() {

            @Override
            public void run() {
                try {
                    RandomAccessFile randomAccessFile = new RandomAccessFile(f, "r");
                    FileChannel fileChannel = randomAccessFile.getChannel();
                    Id id = store.write(fileChannel);
                    System.out.println("(" + num + ") Stored " + f.getPath() + " as " + id.getName() + " after "
                            + (System.currentTimeMillis() - start) + "ms");
                } catch (Exception e) {
                    logger.error("", e);
                }
            }
        };
        ex.execute(job);
    }
}