java线程自带队列的使用以及线程阻塞
生活随笔
收集整理的這篇文章主要介紹了
java线程自带队列的使用以及线程阻塞
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
java線程,設置隊列的大小實現隊列阻塞
public class QueueThreads {private static int nThreads = 4;//Runtime.getRuntime().availableProcessors() * 2 + 1;private static BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(4);//隊列值大小設置為4private static ExecutorService executors = new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, queue, new ThreadFactory() {private final String threadNamePrefix = "si_query_task_";private final AtomicInteger count = new AtomicInteger(1);@Overridepublic Thread newThread(Runnable r) {Thread t = new Thread(Thread.currentThread().getThreadGroup(), r, threadNamePrefix + count.getAndIncrement());//t.setDaemon(true);return t;}});public static void main(String[] args) {for (int i = 0; i < 10; i++) {try {executors.execute(new Thread(new ThreadPoolTest(), "TestThread".concat("" + i)));int threadSize = queue.size();System.out.println("線程隊列大小為-->" + threadSize);} catch(RejectedExecutionException e){System.out.println("阻塞異常");}catch (Exception e) {System.out.println("異常");}}executors.shutdown();}public void run() {synchronized (this) {try {System.out.println("線程名稱:" + Thread.currentThread().getName());Thread.sleep(3000); //休眠是為了讓該線程不至于執行完畢后從線程池里釋放} catch (InterruptedException e) {//e.printStackTrace(); }}}}?
本測試程序的隊列設置為4,線程池的大小為4,循環開啟10個任務執行結果:
分析:有8個任務執行成功了,線程處理完成立馬會處理新的任務,但是出現了兩個阻塞異常,原因是這兩個任務來不及創建就被阻塞了,阻塞的結果就是丟棄。
?
轉載于:https://www.cnblogs.com/zyf-yxm/p/10436142.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java线程自带队列的使用以及线程阻塞的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 邻接表转换邻接矩阵
- 下一篇: Xcode9安装插件,xcode9安装使