DefaultThreadFactory() {
@SuppressWarnings(“removal”)
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = “pool-” +
poolNumber.getAndIncrement() +
“-thread-“;
}
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class CustomThreadPoolExecutorDemo {
public static void main(String[] args) {
// 自定义线程工厂
ThreadFactory threadFactory = new CustomThreadFactory();
// 创建线程池
ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 0,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(),
threadFactory);
// 提交任务
executor.execute(() -> System.out.println(“Task 1”));
executor.execute(() -> System.out.println(“Task 2”));
// 关闭线程池
executor.shutdown();
}
static class CustomThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
// 设置线程优先级为最低优先级
thread.setPriority(Thread.MIN_PRIORITY);
return thread;
}
}
}
public class PriorityBlockingQueueExample {
public static void main(String[] args) {
PriorityBlockingQueue<Task> priorityQueue = new PriorityBlockingQueue<>();
// 添加任务到优先级队列
priorityQueue.add(new Task(“Task 1”, 1));
priorityQueue.add(new Task(“Task 4”, 4));
priorityQueue.add(new Task(“Task 3”, 3));
priorityQueue.add(new Task(“Task 2”, 2));
// 从优先级队列中取出任务并执行
while (!priorityQueue.isEmpty()) {
Task task = priorityQueue.poll();
if (task != null) {
task.execute();
}
}
}
static class Task implements Comparable<Task> {
private String name;
private int priority;
public Task(String name, int priority) {
this.name = name;
this.priority = priority;
}
public void execute() {
System.out.println(“Executing task: ” + name);
}
@Override
public int compareTo(Task o) {
return Integer.compare(this.priority, o.priority);
}
}
}
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class PriorityThreadPool {
public static void main(String[] args) {
BlockingQueue<Runnable> queue = new PriorityBlockingQueue<>(1000);
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1,
0, TimeUnit.SECONDS, queue
);
for (int i = 0; i < 100; i++) {
int finalI = i;
executor.execute(new PriorityTask(i, () -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(“优先级:” + finalI);
}));
}
}
static class PriorityTask implements Runnable, Comparable<PriorityTask> {
private final int priority;
private final Runnable task;
public PriorityTask(int priority, Runnable task) {
this.priority = priority;
this.task = task;
}
@Override
public void run() {
task.run();
}
@Override
public int compareTo(PriorityTask other) {
// 优先级高的任务应该排在前面(数字越小优先级越大)
return Integer.compare(this.priority, other.priority);
}
}
}
微信赞赏支付宝扫码领红包