Java线程池

线程池:就是把多个线程放在一起执行一个任务;

创建一个线程池:

代码

package testDemo;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPool {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//创建一个线程池
		ExecutorService exService = Executors.newCachedThreadPool();
		for(int x = 0; x < 10; x++) {
			int index = x;
			exService.submit(() -> {
				System.out.println(Thread.currentThread().getName()+ "、x = " + index);
			});
		}
		exService.shutdown();//关闭线程池
	}

}
创建单个线程的线程池:newSingleThreadExecutor()
package testDemo;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPool {

	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		//创建一个线程池
		ExecutorService exService = Executors.newSingleThreadExecutor();
		for(int x = 0; x < 10; x++) {
			//Thread.sleep(200);
			int index = x;
			exService.submit(() -> {
				System.out.println(Thread.currentThread().getName()+ "、x = " + index);
			});
		}
		exService.shutdown();
	}

}

创建固定大小的线程池:newFixedThreadExecutor();

package testDemo;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPool {

	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		//创建一个线程池
		ExecutorService exService = Executors.newFixedThreadPool(3);
		for(int x = 0; x < 10; x++) {
			//Thread.sleep(200);
			int index = x;
			exService.submit(() -> {
				System.out.println(Thread.currentThread().getName()+ "、x = " + index);
			});
		}
		exService.shutdown();
	}

}

创建定时调度池:

package testDemo;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ThreadPool {

	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		//创建一个具备有三个大小的定时调度线程池
		ScheduledExecutorService exService = Executors.newScheduledThreadPool(1);
		for(int x = 0; x < 10; x++) {
			//Thread.sleep(200);
			int index = x;
			exService.scheduleAtFixedRate(new Runnable() {
				public void run() {
					System.out.println(Thread.currentThread().getName()+ "、= " + index);
				}
			},3, 2, TimeUnit.SECONDS);//使用的是一个秒的单位,每三秒执行一次
		}
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值