线程组实现原理:
public class CaptureService {
private static final LinkedList<Control> CONTROLS=new LinkedList<>();
public static void main(String[] rgs) {
List<Thread> worker=new ArrayList<>();
Arrays.asList("M1","M2","M3","M4","M5","M6","M7","M8","M9","M10").stream()
.map(CaptureService::creatCaptureThread).forEach(t->{
t.start();
worker.add(t);
});
worker.stream().forEach(t ->{
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
} );
Optional.of("All of capture worker finished").ifPresent(System.out::println);
}
private static Thread creatCaptureThread(String name){
return new Thread(()->{
Optional.of("The worker ["+Thread.currentThread().getName()+"] begin capture data ").ifPresent(
System.out::println);
synchronized (CONTROLS){
while(CONTROLS.size()>5){//保证始终有5个线程在工作
try {
CONTROLS.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
CONTROLS.addLast(new Control());
}
Optional.of("The worker ["+Thread.currentThread().getName()+"] is workering").ifPresent(
System.out::println);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (CONTROLS){
Optional.of("The worker["+Thread.currentThread().getName()+"] END").ifPresent(
System.out::println);
CONTROLS.removeFirst();
CONTROLS.notifyAll();
}
},name);
}
private static class Control{
}
}