创建固定大小的线程池,可以延迟或定时执行任务(调度)


		//创建固定大小的线程池,可以延迟或定时执行任务
		ScheduledExecutorService pool=Executors.newScheduledThreadPool(5);

		for (int i = 0; i < 10; i++) {
			Future<Integer> result =pool.schedule(new Callable<Integer>() {
				@Override
				public Integer call() throws Exception {
					int num = new Random().nextInt(100);
					System.out.println(Thread.currentThread().getName()+":"+num);
					return num;
				}
			},1,TimeUnit.SECONDS);
			System.out.println(result.get());
		}
		pool.shutdown();
		

    public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit);

第一个参数:线程的实现类,第二个,延迟的大小,第三个延迟的单位

猜你喜欢

转载自blog.csdn.net/linhaibing009/article/details/86062573