Java 使用线程池ThreadPool

线程池可以减少创建线程的开销,示例代码如下:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class test {
    static final int MAX_T = 3;
    static ExecutorService pool = Executors.newFixedThreadPool(MAX_T);
    public static void main(String[] args) {
    	pool.execute(new Task());
    	pool.execute(new Task());
    	pool.execute(new Task());
    	pool.shutdown();
	}
    class Task implements Runnable {
        public void run() {
            System.out.println("new thread");
        }
    }
}

如果你想使用Java 8的lamdba表达式的话,可以这样使用:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class test {
    static final int MAX_T = 3;
    static ExecutorService pool = Executors.newFixedThreadPool(MAX_T);
    public static void main(String[] args) {
    	pool.execute(()->{System.out.println("new thread");});
    	pool.execute(()->{System.out.println("new thread");});
    	pool.execute(()->{System.out.println("new thread");});
    	pool.shutdown();
	}
}

猜你喜欢

转载自blog.csdn.net/zhangpeterx/article/details/89452206