multi-thread(三)ExecutorService

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值