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 ));    }}