获取线程的四种方法之-线程池

public class TestThreadPool {

    public static void main(String[] args) {

        //创建线程池
        ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
        //声明执行结果
        ScheduledFuture furture=null;

        try {
            for (int i = 0; i <20; i++) {
                ScheduledFuture result = service.schedule(new Callable(){

                    @Override
                    public Object call() throws Exception {
                         System.out.println(Thread.currentThread().getName());
                        return new Random().nextInt(100);
                    }

                }, 3, TimeUnit.SECONDS);
                //每执行一次就打印一次结果,此结果就是线程的执行结果
                System.err.println(result.get());
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            //关闭线程池
            service.shutdown();
        }
    }
}

 

你可能感兴趣的:(java,基础知识,多线程)