一、单线程版
基于SingleThreadExecutor:仅单线程执行的线程池。
//测试类 public static void main(String[] args) { ExecutorService es = Executors.newSingleThreadExecutor(); es.submit(new SemaphoreService(101,"diyi")); // 关闭线程池: es.shutdown(); } package com.zkdj.urlCheck.spring_boot_1.main.java.service; //线程实现类 public class SemaphoreService implements Runnable { private Integer id; private String name; public SemaphoreService(int id, String name) { this.id = id ; this.name=name; } @Override public void run() { System.out.println("id="+id+" name="+name); } }二、多线程版(固定线程数)
基于FixedThreadPool:线程数固定的线程池;
import java.util.concurrent.*; public class Main { public static void main(String[] args) { // 创建一个固定大小的线程池: ExecutorService es = Executors.newFixedThreadPool(4); for (int i = 0; i < 6; i++) { es.submit(new Task("" + i)); } // 关闭线程池: es.shutdown(); } } class Task implements Runnable { private final String name; public Task(String name) { this.name = name; } @Override public void run() { System.out.println("start task " + name); try { Thread.sleep(1000); } catch (InterruptedException e) { } System.out.println("end task " + name); } }结果:
start task 1 start task 0 start task 3 start task 2 end task 2 end task 3 end task 1 end task 0 start task 4 start task 5 end task 4 end task 5