java线程池与队列

java中使用队列:java.util.Queue

java5 中新增加了 java.util.Queue 接口,用以支持队列的常见操作。该接口扩展了 java.util.Collection 接口。
Queue
使用时要尽量避免 Collection add() remove() 方法,而是要使用 offer() 来加入元素,使用 poll() 来获取并移出元素。它们的优 点是通过返回值可以判断成功与否, add() remove() 方法在失败的时候会抛出异常。 如果要使用前端而不移出该元素,使用 element() 或者 peek() 方法。
值得注意的是 LinkedList 类实现了 Queue 接口,因此我们可以把 LinkedList 当成 Queue 来用。
 
    import java.util.Queue;  
  import java.util.LinkedList;  
  public class TestQueue {  
      public static void main(String[] args) {  
          Queue<String> queue = new LinkedList<String>();  
          queue.offer("Hello");  
          queue.offer("World!");  
          queue.offer(" 你好!");  
          System.out.println(queue.size());  
          String str;  
          while((str=queue.poll())!=null){  
              System.out.print(str);  
          }  
          System.out.println();  
          System.out.println(queue.size());  
      }  
  }  
 
java线程池
(1)
线程池的原理很简单,类似于操作系统中的缓冲区的概念,它的流程如下:先启动若干数量的线程,并让这些线程都处于睡眠状态,当客户端有一个新请求时,就会唤醒线程池中的某一个睡眠线程,让它来处理客户端的这个请求,当处理完这个请求后,线程又处于睡眠状态。
可能你也许会问:为什么要搞得这么麻烦,如果每当客户端有新的请求时,我就创建一个新的线程不就完了?这也许是个不错的方法,因为它能使得你编写代码相对容易一些,但你却忽略了一个重要的问题�D�D性能!就拿我所在的单位来说,我的单位是一个省级数据大集中的银行网络中心,高峰期每秒的客户端请求并发数超过100,如果为每个客户端请求创建一个新线程的话,那耗费的CPU时间和内存将是惊人的,如果采用一个拥有200个线程的线程池,那将会节约大量的的系统资源,使得更多的CPU时间和内存用来处理实际的商业应用,而不是频繁的线程创建与销毁。
 
(2)
实例:
本示例程序由三个类构成,第一个是TestThreadPool类,它是一个测试程序,用来模拟客户端的请求,当你运行它时,系统首先会显示线程池的初始化信息,然后提示你从键盘上输入字符串,并按下回车键,这时你会发现屏幕上显示信息,告诉你某个线程正在处理你的请求,如果你快速地输入一行行字符串,那么你会发现线程池中不断有线程被唤醒,来处理你的请求,在本例中,我创建了一个拥有10个线程的线程池,如果线程池中没有可用线程了,系统会提示你相应的警告信息,但如果你稍等片刻,那你会发现屏幕上会陆陆续续提示有线程进入了睡眠状态,这时你又可以发送新的请求了。

  第二个类是ThreadPoolManager类,顾名思义,它是一个用于管理线程池的类,它的主要职责是初始化线程池,并为客户端的请求分配不同的线程来进行处理,如果线程池满了,它会对你发出警告信息。

  最后一个类是SimpleThread类,它是Thread类的一个子类,它才真正对客户端的请求进行处理,SimpleThread在示例程序初始化时都处于睡眠状态,但如果它接受到了ThreadPoolManager类发过来的调度信息,则会将自己唤醒,并对请求进行处理。
 
import java.io.*;
public class TestThreadPool
{
 public static void main(String[] args)
 {
  try{
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   String s;
   ThreadPoolManager manager = new ThreadPoolManager(5);
   while((s = br.readLine()) != null)
   {
    manager.process(s);
   }
  }catch(IOException e){}
 }
}
 

import java.util.*;
class ThreadPoolManager
{
 private int maxThread;
 public Vector vector;
 public void setMaxThread(int threadCount)
 {
  maxThread = threadCount;
 }
 public ThreadPoolManager(int threadCount)
 {
  setMaxThread(threadCount);
  System.out.println("Starting thread pool...");
  vector = new Vector();
  for(int i = 1; i <= maxThread; i++)
  {
   SimpleThread thread = new SimpleThread(i);
   vector.addElement(thread);
   thread.start();
  }
 }
 public void process(String argument)
 {
  int i;
  for(i = 0; i < vector.size(); i++)
  {
   SimpleThread currentThread = (SimpleThread)vector.elementAt(i);
   if(!currentThread.isRunning()) //非运行状态,即非正在处理业务的状态
   {
    currentThread.setArgument(argument);
    currentThread.setRunning(true);
    System.out.println("Thread "+ (i+1) +" is processing:" +argument);
    return;
   }
  }
  if(i == vector.size())
  {
   System.out.println("pool is full, try in another time.");
  }
 }
}//end of class ThreadPoolManager
 

class SimpleThread extends Thread
{
 private boolean runningFlag;
 private String argument;
 public boolean isRunning()
 {
  return runningFlag;
 }
 public synchronized void setRunning(boolean flag)
 {
  runningFlag = flag;
  if(flag)
   this.notify(); //唤醒线程
 }
 public String getArgument()
 {
  return this.argument;
 }
 public void setArgument(String string)
 {
  argument = string;
 }
 public SimpleThread(int threadNumber)
 {
  runningFlag = false;
  System.out.println("thread " + threadNumber + "started.");
 }
 public synchronized void run()
 {
  try{
   while(true)
   {
    if(!runningFlag)
    {
     this.wait();
    }
    else
    {
     System.out.println("processing " + getArgument() + "... done.");
     sleep(5000);
     System.out.println("Thread is sleeping...");
     setRunning(false);
    }
   }
  } catch(InterruptedException e){
   System.out.println("Interrupt");
  }
 }//end of run()
}//end of class SimpleThread
 
 
Java 队列,线程池
package test01;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolManager
{
    private static ThreadPoolManager tpm = new ThreadPoolManager();
    // 线程池维护线程的最少数量
    private final static int CORE_POOL_SIZE = 4;
    // 线程池维护线程的最大数量
    private final static int MAX_POOL_SIZE = 10;
    // 线程池维护线程所允许的空闲时间
    private final static int KEEP_ALIVE_TIME = 0;
    // 线程池所使用的缓冲队列大小
    private final static int WORK_QUEUE_SIZE = 10;
    // 消息缓冲队列
    Queue<String> msgQueue = new LinkedList<String>();
    // 访问消息缓存的调度线程
    final Runnable accessBufferThread = new Runnable()
    {
        public void run()
        {
            // 查看是否有待定请求,如果有,则创建一个新的AccessDBThread,并添加到线程池中
            if( hasMoreAcquire() )
            {
                String msg = ( String ) msgQueue.poll();
                Runnable task = new AccessDBThread( msg );
                threadPool.execute( task );
            }
        }
    };
    final RejectedExecutionHandler handler = new RejectedExecutionHandler()
    {
        public void rejectedExecution( Runnable r, ThreadPoolExecutor executor )
        {
            System.out.println(((AccessDBThread )r).getMsg()+"消息放入队列中重新等待执行");
            msgQueue.offer((( AccessDBThread ) r ).getMsg() );
        }
    };
    // 管理数据库访问的线程池
    final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
            CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS,
            new ArrayBlockingQueue( WORK_QUEUE_SIZE ), this.handler );
    // 调度线程池
    final ScheduledExecutorService scheduler = Executors
            .newScheduledThreadPool( 1 );
    final ScheduledFuture taskHandler = scheduler.scheduleAtFixedRate(
            accessBufferThread, 0, 1, TimeUnit.SECONDS );
    public static ThreadPoolManager newInstance()
    {
        return tpm;
    }
    private ThreadPoolManager(){}
    private boolean hasMoreAcquire()
    {
        return !msgQueue.isEmpty();
    }
    public void addLogMsg( String msg )
    {
        Runnable task = new AccessDBThread( msg );
        threadPool.execute( task );
    }
}
package test01;
public class AccessDBThread implements Runnable
{
    private String msg;
   
    public String getMsg()
    {
        return msg;
    }
    public void setMsg( String msg )
    {
        this.msg = msg;
    }
   
    public AccessDBThread(){
        super();
    }
   
    public AccessDBThread(String msg){
        this.msg = msg;
    }
    public void run()
    {
        // 向数据库中添加Msg变量值
        System.out.println("Added the message: "+msg+" into the Database");
    }
}
package test01;
import java.util.LinkedList;
import java.util.Queue;
public class TestDriver
{
    ThreadPoolManager tpm = ThreadPoolManager.newInstance();
    public void sendMsg( String msg )
    {
        tpm.addLogMsg( msg + "记录一条日志 " );
    }
    public static void main( String[] args )
    {
        for( int i = 0; i < 100; i++ )
        {
            new TestDriver().sendMsg( Integer.toString( i ) );
        }
    }
}
 
Java 5.0 多线程编程实践
ava5增加了新的类库并发集java.util.concurrent,该类库为并发程序提供了丰富的API多线程编程在Java 5中更加容易,灵活。本文通过一个网服务器模型,来实践Java5的多线程编程,该模型中使用了Java5中的线程池,阻塞队列,可重入锁等,还实践了 Callable, Future等接口,并使用了Java 5的另外一个新特性泛型。

  简介

  本文将实现一个网络服务器模型,一旦有客户端连接到该服务器,则启动一个新线程为该连接服务,服务内容为往客户端输送一些字符信息。一个典型的网络服务器模型如下:

  1. 建立监听端口。

  2. 发现有新连接,接受连接,启动线程,执行服务线程。 3. 服务完毕,关闭线程。

  这个模型在大部分情况下运行良好,但是需要频繁的处理用户请求而每次请求需要的服务又是简短的时候,系统会将大量的时间花费在线程的创建销毁。Java 5的线程池克服了这些缺点。通过对重用线程来执行多个任务,避免了频繁线程的创建与销毁开销,使得服务器的性能方面得到很大提高。因此,本文的网络服务器模型将如下:

  1. 建立监听端口,创建线程池。

  2. 发现有新连接,使用线程池来执行服务任务。

  3. 服务完毕,释放线程到线程池。

  下面详细介绍如何使用Java 5的concurrent包提供的API来实现该服务器。

  初始化

  初始化包括创建线程池以及初始化监听端口。创建线程池可以通过调用java.util.concurrent.Executors类里的静态方法 newChahedThreadPool或是newFixedThreadPool来创建,也可以通过新建一个 java.util.concurrent.ThreadPoolExecutor实例来执行任务。这里我们采用newFixedThreadPool方法来建立线程池。

  ExecutorService pool = Executors.newFixedThreadPool(10);

  表示新建了一个线程池,线程池里面有10个线程为任务队列服务。

  使用ServerSocket对象来初始化监听端口。

  private static final int PORT = 19527;
  serverListenSocket = new ServerSocket(PORT);
  serverListenSocket.setReuseAddress(true);
  serverListenSocket.setReuseAddress(true);

  服务新连接

  当有新连接建立时,accept返回时,将服务任务提交给线程池执行。

  while(true){
  Socket socket = serverListenSocket.accept();
  pool.execute(new ServiceThread(socket));
  }

  这里使用线程池对象来执行线程,减少了每次线程创建和销毁的开销。任务执行完毕,线程释放到线程池。

  服务任务

  服务线程ServiceThread维护一个count来记录服务线程被调用的次数。每当服务任务被调用一次时,count的值自增1,因此 ServiceThread提供一个increaseCount和getCount的方法,分别将count值自增1和取得该count值。由于可能多个线程存在竞争,同时访问count,因此需要加锁机制,在Java 5之前,我们只能使用synchronized来锁定。Java 5中引入了性能更加粒度更细的重入锁ReentrantLock。我们使用ReentrantLock保证代码线程安全。下面是具体代码:

  private static ReentrantLock lock = new ReentrantLock ();
  private static int count = 0;
  private int getCount(){
  int ret = 0;
  try{
  lock.lock();
  ret = count;
  }finally{
  lock.unlock();
  }
  return ret;
  }
  private void increaseCount(){
  try{
  lock.lock();
  ++count;
  }finally{
  lock.unlock();
  }
  }

  服务线程在开始给客户端打印一个欢迎信息,

  increaseCount();
  int curCount = getCount();
  helloString = "hello, id = " + curCount+"\r\n";
  dos = new DataOutputStream(connectedSocket.getOutputStream());
  dos.write(helloString.getBytes());

  然后使用ExecutorService的submit方法提交一个Callable的任务,返回一个Future接口的引用。这种做法对费时的任务非常有效,submit任务之后可以继续执行下面的代码,然后在适当的位置可以使用Future的get方法来获取结果,如果这时候该方法已经执行完毕,则无需等待即可获得结果,如果还在执行,则等待到运行完毕。

  ExecutorService executor = Executors.newSingleThreadExecutor();
  Future future = executor.submit(new TimeConsumingTask());
  dos.write("let's do soemthing other".getBytes());
  String result = future.get();
  dos.write(result.getBytes());

  其中TimeConsumingTask实现了Callable接口

  class TimeConsumingTask implements Callable {
  public String call() throws Exception {
  System.out.println("It's a time-consuming task, you'd better retrieve your result in the furture");
  return "ok, here's the result: It takes me lots of time to produce this result";
  }
  }

  这里使用了Java 5的另外一个新特性泛型,声明TimeConsumingTask的时候使用了String做为类型参数。必须实现Callable接口的call函数,其作用类似与Runnable中的run函数,在call函数里写入要执行的代码,其返回值类型等同于在类声明中传入的类型值。在这段程序中,我们提交了一个Callable的任务,然后程序不会堵塞,而是继续执行dos.write("let's do soemthing other".getBytes());当程序执行到String result = future.get()时如果call函数已经执行完毕,则取得返回值,如果还在执行,则等待其执行完毕。
 服务器端的完整实现

  服务器端的完整实现代码如下:

  package com.andrew;

  import java.io.DataOutputStream;
  import java.io.IOException;
  import java.io.Serializable;
  import java.net.ServerSocket;
  import java.net.Socket;
  import java.util.concurrent.ArrayBlockingQueue;
  import java.util.concurrent.BlockingQueue;
  import java.util.concurrent.Callable;
  import java.util.concurrent.ExecutionException;
  import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;
  import java.util.concurrent.Future;
  import java.util.concurrent.RejectedExecutionHandler;
  import java.util.concurrent.ThreadPoolExecutor;
  import java.util.concurrent.TimeUnit;
  import java.util.concurrent.locks.ReentrantLock;

  public class Server {
  private static int produceTaskSleepTime = 100;
  private static int consumeTaskSleepTime = 1200;
  private static int produceTaskMaxNumber = 100;
  private static final int CORE_POOL_SIZE = 2;
  private static final int MAX_POOL_SIZE = 100;
  private static final int KEEPALIVE_TIME = 3;
  private static final int QUEUE_CAPACITY = (CORE_POOL_SIZE + MAX_POOL_SIZE) / 2;
  private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
  private static final String HOST = "127.0.0.1";
  private static final int PORT = 19527;
  private BlockingQueue workQueue = new ArrayBlockingQueue(QUEUE_CAPACITY);
  //private ThreadPoolExecutor serverThreadPool = null;
  private ExecutorService pool = null;
  private RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.DiscardOldestPolicy();
  private ServerSocket serverListenSocket = null;
  private int times = 5;
  public void start() {
  // You can also init thread pool in this way.
  /*serverThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE,
  MAX_POOL_SIZE, KEEPALIVE_TIME, TIME_UNIT, workQueue,
  rejectedExecutionHandler);*/
  pool = Executors.newFixedThreadPool(10);
  try {
   serverListenSocket = new ServerSocket(PORT);
   serverListenSocket.setReuseAddress(true);

   System.out.println("I'm listening");
   while (times-- > 0) {
    Socket socket = serverListenSocket.accept();
    String welcomeString = "hello";
    //serverThreadPool.execute(new ServiceThread(socket, welcomeString));
    pool.execute(new ServiceThread(socket));
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  cleanup();
  }

  public void cleanup() {
  if (null != serverListenSocket) {
   try {
    serverListenSocket.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  //serverThreadPool.shutdown();
  pool.shutdown();
  }

  public static void main(String args[]) {
  Server server = new Server();
  server.start();
  }
  }

  class ServiceThread implements Runnable, Serializable {
  private static final long serialVersionUID = 0;
  private Socket connectedSocket = null;
  private String helloString = null;
  private static int count = 0;
  private static ReentrantLock lock = new ReentrantLock();

  ServiceThread(Socket socket) {
  connectedSocket = socket;
  }

  public void run() {
  increaseCount();
  int curCount = getCount();
  helloString = "hello, id = " + curCount + "\r\n";

  ExecutorService executor = Executors.newSingleThreadExecutor();
  Future future = executor.submit(new TimeConsumingTask());

  DataOutputStream dos = null;
  try {
   dos = new DataOutputStream(connectedSocket.getOutputStream());
   dos.write(helloString.getBytes());
   try {
    dos.write("let's do soemthing other.\r\n".getBytes());
    String result = future.get();
    dos.write(result.getBytes());
   } catch (InterruptedException e) {
    e.printStackTrace();
   } catch (ExecutionException e) {
    e.printStackTrace();
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   if (null != connectedSocket) {
    try {
     connectedSocket.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   if (null != dos) {
    try {
     dos.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   executor.shutdown();
  }
  }

  private int getCount() {
  int ret = 0;
  try {
   lock.lock();
   ret = count;
  } finally {
   lock.unlock();
  }
  return ret;
  }

  private void increaseCount() {
  try {
   lock.lock();
   ++count;
  } finally {
   lock.unlock();
  }
  }
  }

  class TimeConsumingTask implements Callable {
  public String call() throws Exception {
  System.out.println("It's a time-consuming task, you'd better retrieve your result in the furture");
  return "ok, here's the result: It takes me lots of time to produce this result";
  }

  }

你可能感兴趣的:(职场,123,休闲)