java多线程和队列实例

来源:互联网 发布:java数组的冒泡排序法 编辑:程序博客网 时间:2024/06/02 02:08

第一步:创建一个无边界自动回收的线程池,在此用 JDK提供的ExecutorService类

此线程池。如果线程池的大小超过了处理任务所需要的线程,那么就会回收部分空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。


package com.thread.test;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ThreadPool {private static ExecutorService threadPool = null;public static ExecutorService getThreadPool(){if(threadPool==null){threadPool = Executors.newCachedThreadPool();}return threadPool;}}

第二步:使用单例模式创建一个无界队列,并提供入队的方法

无界队列。使用无界队列(例如,不具有预定义容量的 LinkedBlockingQueue)将导致在所有corePoolSize 线程都忙时新任务在队列中等待。这样,创建的线程就不会超过 corePoolSize。(因此,maximumPoolSize的值也就无效了。)当每个任务完全独立于其他任务,即任务执行互不影响时,适合于使用无界队列;例如,在 Web页服务器中。这种排队可用于处理瞬态突发请求,当命令以超过队列所能处理的平均数连续到达时,此策略允许无界线程具有增长的可能性。

package com.thread.test;import java.util.concurrent.LinkedBlockingQueue;public class TaskQueue {private static  LinkedBlockingQueue queues = null;public static LinkedBlockingQueue getTaskQueue(){if(queues==null){queues =  new LinkedBlockingQueue();System.out.println("初始化 队列");}return queues;}public static void add(Object obj){if(queues==null)queues =  getTaskQueue();queues.offer(obj);System.out.println("-------------------------------");System.out.println("入队:"+obj);}}

第三步:提供一个入队的线程,实际使用中的生产者

package com.thread.test;public class Produce implements Runnable {private static volatile int i=0;private static volatile boolean isRunning=true;public void run() {while(isRunning){TaskQueue.add(Integer.valueOf(i+""));Produce.i++;try {Thread.sleep(1*1000);} catch (InterruptedException e) {e.printStackTrace();}}}}

第四步:提供一个出队的线程,实际使用中的消费者

package com.thread.test;public class Consumer implements Runnable {private static Consumer consumer;public static volatile boolean isRunning=true;public void run() {while(Thread.currentThread().isInterrupted()==false && isRunning)          {  try {System.out.println("出队"+TaskQueue.getTaskQueue().take());Thread.sleep(1*1000);  } catch (InterruptedException e) {e.printStackTrace();}        }}public static Consumer getInstance(){if(consumer==null){consumer = new Consumer();System.out.println("初始化消费线程");}return consumer;}}

第五步:启动生产消费策略

package com.thread.test;import java.util.concurrent.ExecutorService;import java.util.concurrent.LinkedBlockingQueue;public class Test {public static void main(String[] args) {ExecutorService threadPool = ThreadPool.getThreadPool();Produce consumer2 = new Produce();threadPool.execute(consumer2);Consumer consumer=Consumer.getInstance();threadPool.execute(consumer);}}



0 0
原创粉丝点击