天天看点

java线程池

java1.5之后追加了一个并发访问的程序包: java.util.concurrent。对于此线程池操作的核心类和接口就定义在此包中。

这里有2个核心的接口:

1、普通的执行线程池定义: java.util.concurrent.ExecutorService;

2、调度线程池:java.util.concurrent.ScheduledExecutorService;

一般可以使用 java.util.concurrent.Executors类完成线程池的创建

3、创建无大小限制的线程池: java.util.concurrent.ExecutorService newCachedThreadPool();

4、创建固定大小的线程池:java.util.concurrent.ExecutorService newFixedThreadPool(int nThreads);

5、创建单线程池:java.util.concurrent.ExecutorService newSingleThreadScheduledExecutor();

6、创建定时调度池:newScheduledThreadPool()

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.Test;

public class testThreadPool {

    @Test
    public void test1() {
        //创建一个线程池的模型
        //ExecutorService executorService = Executors.newCachedThreadPool();  //创建无大小限制的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);  //创建固定大小的线程池
        for(int x=0;x<10;x++){
            final int index=x;
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+", x="+index);
                }
            });
        }
        executorService.shutdown();
    }

    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);  //创建定时调度池
        for(int x=0;x<10;x++){
            final int index=x;
            executorService.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+", x="+index);
                }
            }, 3, 2, TimeUnit.SECONDS);
        }
    }
}