JAVA线程池样例

来源:互联网 发布:vb安装win10 编辑:程序博客网 时间:2024/06/05 05:21

主要抄了三种:

newSingleThreadExecutor

newCachedThreadPool()

newFixedThreadPool(int)


0fce6f058f09c352504418099c90ba3e784a9aeb


我有几张阿里云幸运券分享给你,用券购买或者升级阿里云相应产品会有特惠惊喜哦!把想要买的产品的幸运券都领走吧!快下手,马上就要抢光了。

package demo.thread;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ThreadMain {public static void main(String[] args) throws Exception {ExecutorService sexecutor = Executors.newSingleThreadExecutor();for (int i = 0; i < 5; i++) {final int no =i;Runnable runnable = new Runnable() {public void run() {try {System.out.println("Single executor into " + no);Thread.sleep(1000L);System.out.println("Single executor end " + no);} catch (InterruptedException e) {e.printStackTrace();}}};sexecutor.execute(runnable);}sexecutor.shutdown();ExecutorService cexecutor = Executors.newCachedThreadPool();for (int i = 0; i < 20; i++) {final int no =i;Runnable runnable = new Runnable() {public void run() {try {System.out.println("Cached executor into " + no);Thread.sleep(1000L);System.out.println("Cached executor end " + no);} catch (InterruptedException e) {e.printStackTrace();}}};cexecutor.execute(runnable);}cexecutor.shutdown();ExecutorService fexecutor = Executors.newFixedThreadPool(5);for (int i = 0; i < 20; i++) {final int no =i;Runnable runnable = new Runnable() {public void run() {try {System.out.println("Fixed executor into " + no);Thread.sleep(1000L);System.out.println("Fixed executor end " + no);} catch (InterruptedException e) {e.printStackTrace();}}};fexecutor.execute(runnable);}fexecutor.shutdown();System.out.println("The main thread end.");}}
原文链接