详细内容
本篇文章给大家带来的内容是关于java多线程的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
1:
ExecutorService executor = new ThreadPoolExecutor(5, 5, 60, TimeUnit.SECONDS, new LinkedBlockingQueue());
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() {
// 操作
}
}