zoukankan      html  css  js  c++  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);//队列值大小设置为4
    
        private 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);
    
            @Override
            public 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个任务执行成功了,线程处理完成立马会处理新的任务,但是出现了两个阻塞异常,原因是这两个任务来不及创建就被阻塞了,阻塞的结果就是丢弃。

  • 相关阅读:
    Adobe官方推荐的ActionScript的最佳做法和编码约定
    从Array extends 时要使用 dynamic 关键字
    java本质——内存分布
    函数参数传递
    AS3.0连接FMS2.0
    C#序列化和反序列化代码
    XmlSerializer 对象的Xml序列化和反序列化
    ASP.NET2.0服务器控件之Render方法
    加密技术在企业数据安全中的应用
    IEnumerable IEnumerator 接口
  • 原文地址:https://www.cnblogs.com/zyf-yxm/p/10436142.html
Copyright © 2011-2022 走看看