⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 concurrencyexample.java

📁 一步 教你学会java 完成一个完整的SWT系统 是本人学习java时按教程一步一步写下来的咯
💻 JAVA
字号:
/** *  Concurrency utilities (JSR-166) example **/package threadpool;import java.net.*;import java.io.*;import java.util.concurrent.*;public class ConcurrencyExample {  private final static int MAX_THREADS = 2;  private final ServerSocket serverSocket;  private final ThreadPoolExecutor pool;  private final ArrayBlockingQueue<Runnable> workQueue;  /**   *  Constructor   **/  public ConcurrencyExample(int port, int poolSize) throws IOException {    /*  Create a new ServerSocket to listen for incoming connections  */    serverSocket = new ServerSocket(port);    /*  In order to create a pool of threads we must first have a queue     *  that will be used to hold the work tasks before they are executed     *  For this example we use a ArrayBlockingQueue that can hold the      *  same number of tasks as we have maximum threads     */    workQueue = new ArrayBlockingQueue<Runnable>(MAX_THREADS);    /*  Now create the ThreadPool.  The initial and maximum number of      *  threads are the same in this example     */    pool = new ThreadPoolExecutor(MAX_THREADS, MAX_THREADS,      60, TimeUnit.SECONDS, workQueue);  }  /**   *  Service requests   **/  public void serviceRequests() {    int count = 1;    int qLength = 0;    try {      for (;;) {        if ((qLength = workQueue.size()) > 0)          System.out.println("Queue length is " + qLength);        pool.execute(new ConnectionHandler(serverSocket.accept(), count++));      }    } catch (IOException ioe) {      System.out.println("IO Error in ConnectionHandler: " + ioe.getMessage());      pool.shutdown();    }  }  /**   *  Main entry point   *   * @param args Command line arguments   **/  public static void main(String[] args) {    System.out.println("Listening for connections...");    ConcurrencyExample ce = null;    try {      ce = new ConcurrencyExample(8100, 4);      ce.serviceRequests();    } catch (IOException ioe) {      System.out.println("IO Error creating listener: " + ioe.getMessage());    }  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -