JUC学习笔记(10)—线程池

public class ExecutorsDemo
{
	public static void main(String[] args)
	{
		ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
		ScheduledFuture result = null;
		try 
		{
			for (int i = 1; i <=15; i++) 
			{
				result = service.schedule(() -> {
					System.out.print(Thread.currentThread().getName());
					return new Random().nextInt(10);
				}, 2, TimeUnit.SECONDS);
				System.out.println("  ********result: "+result.get());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			service.shutdown();
		}		
	}

	public static void testThreadPool()
	{
		//ExecutorService service = Executors.newFixedThreadPool(5);//一池5线程
		//ExecutorService service = Executors.newSingleThreadExecutor();//一池1线程
		ExecutorService service = Executors.newCachedThreadPool();//一池N线程
		Future result = null;
		
		try 
		{
			for (int i = 1; i <=15; i++) 
			{
				result = service.submit( () -> {
					Thread.sleep(400);
					System.out.print(Thread.currentThread().getName());
					return new Random().nextInt(10);
				} );
				System.out.println("  ********result: "+result.get());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			service.shutdown();
		}
	}
}

 

你可能感兴趣的:(JAVA并发编程,java)