线程池一直是一个非常关键的知识点 用线程池在项目处理一些高并发 相信是比较常见的 或者封装自己的框架的时候也是必须的.
如果对线程的api比较熟悉的话 这个对象一定不陌生 翻译:信号量
可以限定线程个数 来处理高并发 ,
//参数 5 是锁的个数
Semaphore semaphore = new Semaphore(5);
//获取一把锁
semaphore.acquire();
//run方法运行完以后 防止内存泄漏需要释放锁
semaphore.release();//释放一把锁
完整代码如下
ps:java.util.concurrent并发包所有的都是 java大牛Doug Lea写的
import java.util.concurrent.Semaphore
public class ThreadPoolTest {
//参数 5 是锁的个数
Semaphore semaphore = new Semaphore(5);
public static void main(String args[]) {
for (int i = 0; i < 110; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
method();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
private static void method() throws InterruptedException {
semaphore.acquire(); //获取一把锁
System.out.println("ThreadName" + Thread.currentThread().getName() + "过来了");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ThreadName" + Thread.currentThread().getName() + "出去了");
//run方法运行完以后 防止内存泄漏需要释放锁
semaphore.release();//释放一把锁
}
}
java自带的线程池的工具类大家都比较熟悉了 用executors创建线程池分别为:
//缓存线程池
Executors executors = Executors.newCachedThreadPool();
//固定线程个数的线程池
Executors executors1 = Executors.newFixedThreadPool();
//计划线程数的线程池
Executors executors2 = Executors.newScheduledThreadPool();
//单个线程的线程池
Executors executors3 = Executors.newSingleThreadExecutor();
CachedThreadPool()来分析 其内部是返回一个封装的ThreadPoolExecutor对象,另外3个内部同理
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
FixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
ScheduledThreadPool
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE,
DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
new DelayedWorkQueue());
}
SingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
使用线程池来执行任务测试:
public class ThreadPoolTest {
private static ExecutorService executors = Executors.newCachedThreadPool();
// Executors executors1 = Executors.newFixedThreadPool();
// Executors executors2 = Executors.newScheduledThreadPool();
// Executors executors3 = Executors.newSingleThreadExecutor();
public static void main(String args[]){
for (int i = 0;i<110;i++){
executors.execute(new Runnable() {
@Override
public void run() {
method();
}
});
}
}
private static void method() {
System.out.println("ThreadName"+Thread.currentThread().getName()+ "过来了");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ThreadName"+Thread.currentThread().getName()+ "出去了");
}
}
自定义线程池
/*int corePoolSize, 核心线程池大小
int maximumPoolSize, 最大线程池大小
long keepAliveTime, 线程存活时间(执行完任务后销毁等待时间)
TimeUnit unit, 时间单位
BlockingQueue workQueue, 工作队列
ThreadFactory threadFactory 线程工厂
ThreadPoolExecutor(int, int, long, TimeUnit, BlockingQueue, ThreadFactory)
*/
1 创建ThreadPoolExecutor对象 根据参数类型添加参数
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 10, 1, TimeUnit.SECONDS,
blockingQueue, threadFactory);
2 LinkedBlockingQueue
//BlockingQueue 单端队列
//BlockingDeque 双端队列
//new StringBuffer(100); 动态分配
/*public StringBuffer(String str) {
super(str.length() + 16);
append(str);
}*/
//100是该容器的最大上限 runnale泛型参数
//AarryBlockingQueue 链表结构
//增删比较频繁 所以用链表结构的LinkedblockQueue
LinkedBlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>(100);
3 ThreadFactory
ThreadFactory threadFactory = new ThreadFactory() {
//int i = 0;
//thread.setName("MyThread"+ i++); i++ 不是线程安全的
//synchronized 关键字 每次执行一个线程 影响性能
//使用包装类 原子性的int线程安全的包装类
AtomicInteger atomicInteger = new AtomicInteger(0);
@Override
public Thread newThread(@NonNull Runnable r) {
//创建线程 把r赋值线程
Thread thread = new Thread(r);
//线程Id
//getAndIncrement() == i++ incrementAndGet()== ++i
thread.setName("MyThread=" + atomicInteger.getAndIncrement());
return thread;
}
};
for循环代码
for (int i = 0; i < 110; i++) {
poolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
method();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
public class ThreadPoolTest {
private static ExecutorService executors = Executors.newCachedThreadPool();
// Executors executors1 = Executors.newFixedThreadPool();
// Executors executors2 = Executors.newScheduledThreadPool();
// Executors executors3 = Executors.newSingleThreadExecutor();
//信号量
//static Semaphore semaphore = new Semaphore(5);
public static void main(String args[]) {
LinkedBlockingQueue blockingQueue = new LinkedBlockingQueue<>(100);
ThreadFactory threadFactory = new ThreadFactory() {
//int i = 0;
//thread.setName("MyThread"+ i++); i++ 不是线程安全的
//synchronized 关键字 每次执行一个线程 影响性能
//使用包装类 原子性的int线程安全的包装类
AtomicInteger atomicInteger = new AtomicInteger(0);
@Override
public Thread newThread(@NonNull Runnable r) {
//创建线程 把r赋值线程
Thread thread = new Thread(r);
//线程Id
//getAndIncrement() == i++ incrementAndGet()== ++i
thread.setName("MyThread=" + atomicInteger.getAndIncrement());
return thread;
}
};
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 10, 1, TimeUnit.SECONDS,
blockingQueue, threadFactory);
for (int i = 0; i < 110; i++) {
poolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
method();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
private static void method() throws InterruptedException {
System.out.println("ThreadName" + Thread.currentThread().getName() + "过来了");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ThreadName" + Thread.currentThread().getName() + "出去了");
}
}
github地址
转载请注明出处 https://blog.csdn.net/LyueP/article/details/88664207