Java 线程池

1 什么是Java 线程池

Java线程池 表示一组正在等待作业并多次重复使用的工作线程。

如果是线程池,则会创建一组固定大小的线程。服务提供商从线程池中拉出一个线程并为其分配作业。作业完成后,线程再次包含在线程池中。

2 Java 线程池的优势

由于无需创建新线程,因此拥有更好的性能,可以节省时间。

3 Java 线程池的应用场景

在用户请求Servlet和JSP时,其中Tomcat容器创建一个线程池来处理用户请求。

4 Java 线程池的例子

让我们看一个使用ExecutorService和Executors的Java线程池的简单示例。

WorkerThread.java:

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 *  Java 线程池的例子
 */
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class WorkerThread implements Runnable {

    private String message;
    public WorkerThread(String s){
        this.message=s;
    }
    public void run() {
        System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);
        processmessage();//call processmessage method that sleeps the thread for 2 seconds
        System.out.println(Thread.currentThread().getName()+" (End)");//prints thread name
    }
    private void processmessage() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
TestThreadPool.java:
package com.yiidian;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 *  Java 线程池的例子
 */
public class TestThreadPool {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);//creating a pool of 5 threads
        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread("" + i);
            executor.execute(worker);//calling execute method of ExecutorService
        }
        executor.shutdown();
        while (!executor.isTerminated()) {   }

        System.out.println("Finished all threads");
    }
}

输出结果为:

pool-1-thread-1 (Start) message = 0
pool-1-thread-2 (Start) message = 1
pool-1-thread-3 (Start) message = 2
pool-1-thread-4 (Start) message = 3
pool-1-thread-5 (Start) message = 4
pool-1-thread-1 (End)
pool-1-thread-1 (Start) message = 5
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = 6
pool-1-thread-4 (End)
pool-1-thread-4 (Start) message = 7
pool-1-thread-3 (End)
pool-1-thread-3 (Start) message = 8
pool-1-thread-5 (End)
pool-1-thread-5 (Start) message = 9
pool-1-thread-1 (End)
pool-1-thread-2 (End)
pool-1-thread-4 (End)
pool-1-thread-3 (End)
pool-1-thread-5 (End)
Finished all threads

 

热门文章

优秀文章