multi-thread(三)ExecutorService
来源:互联网 发布:居则曰 不吾知也翻译 编辑:程序博客网 时间:2024/06/10 09:18
1, 线程池调度线程,而不是new Thread.startI()调度
public class TestExecutorService { public static void main( String[] args ) { // 同时最多只能有2个线程 nThreads ExecutorService pool = Executors.newFixedThreadPool( 2 ); Thread t1 = new MyThread(); Thread t2 = new MyThread(); Thread t3 = new MyThread(); // 将线程放入池中进行执行 pool.execute( t1 );// pool.execute( t2 ); pool.execute( t3 ); // 关闭线程池 pool.shutdown(); }}class MyThread extends Thread { @Override public void run() { System.out.println( Thread.currentThread() + "is running" ); try { Thread.sleep( 1000 ); } catch ( InterruptedException e ) { e.printStackTrace(); } }}
2,线程关闭,Futrue,Callable
public class TestExecutorService { public static void main( String[] args ) throws Exception { ExecutorService threadPool = Executors.newSingleThreadExecutor(); Future<Boolean> future = threadPool.submit( new Callable<Boolean>() { @Override public Boolean call() throws Exception { System.out.println( "start......" ); Thread.sleep( 1000 * 10 ); System.out.println( "end........" ); return Boolean.TRUE; } } ); System.out.println( "future get start....." ); // time out 后,线程仍会执行,// boolean rst = future.get( 2, TimeUnit.SECONDS );// System.out.println("Callable. run end = "+rst); // 测试mian线程threadPool不会主动关闭,不用future.get( 2, TimeUnit.SECONDS );一次只测一个 // future.get(); System.out.println( "future get end....." ); threadPool.shutdown(); // Callable中的方法,没有执行完就退出了 System.out.println(future.cancel( true )); }}
阅读全文
0 0
- multi-thread(三)ExecutorService
- Thread----ExecutorService
- multi-thread(一)基础知识
- multi-thread(二)ThreadGroup
- multi-thread(七)ReentrantReadWriteLock
- multi-thread(八)Semaphore
- multi-thread(九)CountDownLatch
- multi-thread(十)CyclicBarrier
- multi-thread
- Multi-Thread
- multi thread
- Thread & ExecutorService & ThreadPoolExecutor 总览
- Python multi-process VS multi-thread (多核CPU利用率)
- [thread] multi-thread, thread attributes
- Python(11):多线程(Multi-Thread)
- multi-thread(六)ReentrantLock,Condition
- ExecutorService引发的血案(三)ThreadPoolExecutor
- ExecutorService产生的Thread命名
- centos 6.4 安装 nginx
- Linux tar 命令
- jetty tomcat
- BZOJ1072 [SCOI2007]排列perm
- linux 下装 mono,使apache 运行 asp.net
- multi-thread(三)ExecutorService
- Timer,TimerTask的用法
- Java核心代码(二)构造+语句执行顺序
- 二维数组
- NOIP 2017 提高组 初赛
- BZOJ1426 玄学概率DP
- 常用java路径
- Reserved-6
- MongoDB常用查询