Home >Java >javaTutorial >java multithreading code example

java multithreading code example

不言
不言forward
2019-01-30 11:29:313993browse

This article brings you code examples about Java multi-threading. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1:

ExecutorService executor = new ThreadPoolExecutor(5, 5, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
list.forEach(a -> {
    executor.submit(() -> {
        //    业务操作
    });

});
executor.shutdown();

try {
    boolean loop = true;
    do {
        loop = !executor.awaitTermination(2, TimeUnit.SECONDS);
    } while (loop);
} catch (InterruptedException e) {
    Loggers.BIZ.error("error", e);
}

2:

// 产生一个 ExecutorService 对象,这个对象带有一个大小为 poolSize 的线程池,若任务数量大于 poolSize ,任务会被放在一个 queue 里顺序执行。
ExecutorService executor = Executors.newFixedThreadPool(5);

for (Integer num = 0; num < 999; num++) {
    Runnable runner = new ThreadTest(num);
    executor.execute(runner);
}

executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);

ThreadTest

/**
 * 多线程扩展方法
 * */
public class ThreadTest implements Runnable {
    /**
     * table对象
     */
    private Integer num;

    public RecognitionTableThread(Integer num) {
        this.num = num;
    }

    @Override
    public void run() {
        //    操作
    }
}

The above is the detailed content of java multithreading code example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete