public class ThreadPoolTest { public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 1; i <=10 ; i++) { final int task = i; executorService.execute(new Runnable() { @Override public void run() { for (int j = 1; j <= 10; j++) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " is for " + " j= " + j +" task = " + task); } } }); } //executorService.shutdown(); } } 代码很简单就不解释了
AI 代码解读
看一下第二种方式
public class SemaphoreTest { public static void main(String[] args) { ExecutorService service = Executors.newCachedThreadPool(); final Semaphore s = new Semaphore(3); for (int i = 0; i < 10; i++) {// 开是个对象 Runnable runnable = new Runnable() { @Override public void run() { try { s.acquire();// 判断对象的信号灯,亮就代表有线程 }catch (InterruptedException e) { e.printStackTrace(); } System.out.println("线程" + Thread.currentThread() + "进入,当前已有" + s.availablePermits()); try { Thread.sleep((long)(Math.random()*10000)); }catch (InterruptedException e){ e.printStackTrace(); } System.out.println("线程"+Thread.currentThread()+"即将离开"); s.release(); System.out.println("线程"+Thread.currentThread()+"线程已离开,当前已有"+s.availablePermits()); } }; service.execute(runnable);// 把对象装线程池 } } }