Home > Java > javaTutorial > body text

java multithreading code example

不言
Release: 2019-01-30 11:29:31
forward
3966 people have browsed it

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);
}
Copy after login

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);
Copy after login

ThreadTest

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

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

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

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

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template