【多线程】线程池的使用

版权声明:本文为博主原创文章,如需转载请标明来源。 https://blog.csdn.net/sinat_35821285/article/details/79961200

线程池的作用:

限制系统中执行线程的数量,减少内存的消耗,减轻服务器负荷。



newFixedThreadPool

ExecutorService pool=Executors.newFixedThreadPool(2);
	Thread t1=new Thread(new ThreadDemo1("线程A"));
	Thread t2=new Thread(new ThreadDemo1("线程B"));
	Thread t3=new Thread(new ThreadDemo1("线程C"));
	Thread t4=new Thread(new ThreadDemo1("线程D"));
	//放入线程池
	 pool.execute(t1);
	 pool.execute(t2);
	 pool.execute(t3);
	 pool.execute(t4);
	//关闭线程池
	 pool.shutdown();



newCachedThreadPool

 ExecutorService pool=Executors.newCachedThreadPool();
	   
	   for(int i=0;i<10;i++){
		   final int index=i;
		   try {
			Thread.sleep(1000);
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	   
	   
	   pool.execute(new Runnable(){

		@Override
		public void run() {
            System.out.println(index);			
		}});
	}

newScheduledThreadPool

ScheduledExecutorService pool=Executors.newScheduledThreadPool(5);
		pool.schedule(new Runnable() {
			@Override
			public void run() {
          System.out.println("延迟3秒");				
			}
		}, 3, TimeUnit.SECONDS);
		
		
		pool.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
         System.out.println("延迟1秒,每个执行3秒");				
			}
		}, 1, 3, TimeUnit.SECONDS);

newSingleThreadExecutor

ExecutorService singleThreadExecutor=Executors.newSingleThreadExecutor();
		for(int i=0;i<5;i++){
			final int index=i;
			singleThreadExecutor.execute(new Runnable(){

				@Override
				public void run() {
					try {
						Thread.sleep(2000);
						System.out.println(Thread.currentThread().getName()+"  : "+index);
					} catch (InterruptedException e) {
						e.printStackTrace();
						
					}
				}});
		}


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页