java四种线程池初探

来源:互联网 发布:淘宝上好看的女鞋店铺 编辑:程序博客网 时间:2024/06/08 02:50
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;/** * 线程池的比较 * @author TMAC-J * 通过源码分析可知:所有线程池都实现了ExecutorService接口,Executors通过很多层封装和调用最终通过工厂模式产生线程,真正创建的应该是ThreadPoolExecutor * 此类有很多参数(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()))等, * 而真正在活动的线程是通过ThreadPoolExecutor中的HashSet<worker>来装。 * */public class Test{static int i = 0;public static void main(String[] args) {ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();for(int j = 0;j<10;j++){TestThread testThread = new TestThread();newSingleThreadExecutor.execute(testThread);//底层通过将ThreadPoolExecutor设置成容量为1,//然后将要执行的线程全部放在Qeuen中,利用FIFO的特性达到newSingleThreadExecutor一个一个线程依次执行的目的}}static class TestThread implements Runnable{@Overridepublic void run() {i++;System.out.println("Thread is running"+i);}}}
public class Test{static int i = 0;public static void main(String[] args) {ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(1);for(int j = 0;j<10;j++){TestThread testThread = new TestThread();i++;newScheduledThreadPool.scheduleAtFixedRate(testThread, 1, 3,TimeUnit.SECONDS);//延时1S,每3S执行一次}}static class TestThread implements Runnable{@Overridepublic void run() {System.out.println("Thread is running"+i);}}}
public class Test{static int i = 0;public static void main(String[] args) {ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(3);for(int j = 0;j<10;j++){TestThread testThread = new TestThread();i++;newFixedThreadPool.execute(testThread);//并发执行3个线程,个人感觉 newScheduledThreadPool也可以达到这种效果,
                                                                //把延时设置为0,确定线程池大小,并且试验有用 }}static class TestThread implements Runnable{@Overridepublic void run() {System.out.println("Thread is running"+i);try {Thread.sleep(10000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
public class Test{static int i = 0;public static void main(String[] args) {ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();for(int j = 0;j<10;j++){TestThread testThread = new TestThread();i++;newCachedThreadPool.execute(testThread);//自动调整大小,如果线程池中有空的线程,就复用,若没有,就新建 //通过源码可知每个空闲线程的存活时间为60S}}static class TestThread implements Runnable{@Overridepublic void run() {System.out.println("Thread is running"+i);try {Thread.sleep(10000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}

0 0
原创粉丝点击