发布网友 发布时间:2022-04-22 03:58
共1个回答
热心网友 时间:2022-04-11 02:37
//在Android中实现线程池,首先需要实现一个线程工厂(ThreadFactory)的子类,具体实现方式如下所示(PriorityThreadFactory.Java):
import android.os.Process;
/**
* A thread factory that create threads with a given thread priority
* @author jony
* @version 1.0
*/
public class PriorityThreadFactory implements ThreadFactory{
private final String mName;
private final int mPriority;
private final AtomicInteger mNumber = new AtomicInteger();
public PriorityThreadFactory(String name, int priority) {
mName = name;// 线程池的名称
mPriority = priority;//线程池的优先级
}
@Override
public Thread newThread(Runnable r) {
return new Thread(r, mName +"-"+mNumber.getAndIncrement()){
@Override
public void run() {
// 设置线程的优先级
Process.setThreadPriority(mPriority);
super.run();
}
};
}
}
//以上是创建线程池的一个工具类,接下来为大家介绍本篇文章的重点,线程池的实现方式,具体实现方式如下所示(MyThreadPool.java):
package com.tcl.actionbar;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
package com.tcl.actionbar;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ThreadFactory;
// 线程池的实现方式
public class MyThreadPool {
private final static int POOL_SIZE = 4;// 线程池的大小最好设置成为CUP核数的2N
private final static int MAX_POOL_SIZE = 6;// 设置线程池的最大线程数
private final static int KEEP_ALIVE_TIME = 4;// 设置线程的存活时间
private final Executor mExecutor;
public MyThreadPool() {
// 创建线程池工厂
ThreadFactory factory = new PriorityThreadFactory("thread-pool", android.os.Process.THREAD_PRIORITY_BACKGROUND);
// 创建工作队列
BlockingQueue<Runnable> workQueue = new LinkedBlockingDeque<Runnable>();
mExecutor = new ThreadPoolExecutor(POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, workQueue, factory);
}
// 在线程池中执行线程
public void submit(Runnable command){
mExecutor.execute(command);
}
}