什么時候用多線程弄砍?
image.png
程序執(zhí)行結果:
image.png
先說一下此處的打印殿雪,第一個參數是當前線程名稱,由于線程之間是異步執(zhí)行,有的還沒創(chuàng)建好牵触,有的后來居上就執(zhí)行完了草娜,打印線程的名稱會這樣,第二個參數是優(yōu)先級猴凹,默認都是5酝豪,第三個參數是線程組名稱。
package com.furtech.javautils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.LinkedBlockingQueue;
/**
* @des 線程池的簡單實現(可擴展)
*
* @author 719383495@qq.com | 719383495qq@gmail.com | 有問題可以郵箱或者github聯系我
* @date 2019/8/4 13:55
*/
public class ThreadPool {
/**@des logger */
private static final Logger logger = LoggerFactory.getLogger(ThreadPool.class);
private final int poolSize;
private final LinkedBlockingQueue queue;
private final PoolWorker[] runable;
public ThreadPool(int poolSize) {
this.poolSize = poolSize;
queue = new LinkedBlockingQueue();
runable = new PoolWorker[poolSize];
for (int i = 0; i < poolSize; i++) {
runable[i] = new PoolWorker();
new Thread(runable[i], "pool-" + i).start();
}
}
public void execute(Runnable task) {
synchronized (queue) {
queue.add(task);
queue.notify();
}
}
private class PoolWorker implements Runnable {
@Override
public void run() {
Runnable task ;
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
queue.wait();
} catch (Exception e) {
logger.info("exception in queue waiting :{}",e.getMessage());
}
}
task = (Runnable) queue.poll();
}
try {
task.run();
} catch (RuntimeException e) {
logger.info("run exception : {}", e.getMessage());
}
}
}
}
}
class ThreadPoolMain {
public static void main(String[] args) {
ThreadPool pool = new ThreadPool(5);
int MaxSize = 100;
for (int i = 0; i < MaxSize; i++) {
pool.execute(() -> System.out.println(Thread.currentThread()));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
我的博客即將同步至騰訊云+社區(qū)精堕,邀請大家一同入駐:https://cloud.tencent.com/developer/support-plan?invite_code=39wh3ifp3dkws