开启了9个线程分别取去执行任务,但同时只能有3个线程处于运行中,其余的处于block状态,等某个线程运行完后,再将block状态的线程唤醒去执行,直到所有的任务执行完成,这样做的一个原因是当系统中有大量线程,比如有10000个线程在运行时,CPU在线程之间切换可能导致效率很低,我只让有限的线程比如10个线程运行,减少线程间切换,可以提高效率。要求不使用线程池实现
public class Test { //CONTROLS锁 final static private LinkedList<Control> CONTROLS = new LinkedList<>(); private final static int MAX_WORKER = 2; public static void main(String[] args) { List<Thread> worker = new ArrayList<>(); Arrays.asList("T1", "T2", "T3", "T4", "T5", "T6", "T7", "T8", "T9").stream() .map(Test::createCaptureThread).forEach(t -> { t.start(); worker.add(t); }); worker.stream().forEach(t -> { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); System.out.println("All of capture work finished"); } private static Thread createCaptureThread(String name) { return new Thread(() -> { System.out.println("The worker 【" + Thread.currentThread().getName() + " 】 BEGIN capture data "); synchronized (CONTROLS) { while (CONTROLS.size() > MAX_WORKER) { try { CONTROLS.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } CONTROLS.addLast(new Control()); } System.out.println("The worker 【" + Thread.currentThread().getName() + " 】 is working ..."); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (CONTROLS) { System.out.println("The worker 【" + Thread.currentThread().getName() + " 】 END capture data "); CONTROLS.removeFirst(); CONTROLS.notifyAll(); } }, name); } private static class Control { } }