Java 多线程案例 (2)

sleep not need to be wakeup, but wait must need to notify.

数据采集多线程案例 package concurency.chapter8; import java.util.*; /** * @author draymonder * @Date 2019/02/14 */ public class DataCapture { private static final Object LOCK = new Object(); private static final int MAX = 5; private static LinkedList<Controller> list = new LinkedList<>(); public static void main(String[] args) { ArrayList<Thread> threads = new ArrayList<>(); // 开辟10个线程, 每个线程采集数据 Arrays.asList("Mac1", "Mac2", "Mac3", "Mac4", "Mac5", "Mac6", "Mac7", "Mac8", "Mac9", "Mac10").stream() .map(DataCapture::createDataCaptureThread).forEach(dataCaptureThread->{ dataCaptureThread.start(); // 放入threads List中 threads.add(dataCaptureThread); }); // main线程等这10个线程 执行完再结束 threads.forEach((thread)->{ try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); Optional.of("the data capture have finished").ifPresent(System.out::println); } private static Thread createDataCaptureThread(String name) { return new Thread(()->{ Optional.of(Thread.currentThread().getName() + " is begin").ifPresent(System.out::println); // 如果大于等于5个线程,后面的线程就等待 synchronized (LOCK) { while(list.size() >= MAX) { try { LOCK.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } list.add(new Controller()); } Optional.of(Thread.currentThread().getName() + " is running").ifPresent(System.out::println); try { Thread.sleep(10_000); } catch (InterruptedException e) { e.printStackTrace(); } // 执行完毕 synchronized (LOCK) { Optional.of(Thread.currentThread().getName() + " end").ifPresent(System.out::println); // 执行完 删除一个 list.removeFirst(); LOCK.notifyAll(); } },name); } static class Controller{} }

执行结果

Mac1 is begin Mac1 is running Mac2 is begin Mac2 is running Mac3 is begin Mac3 is running Mac4 is begin Mac4 is running Mac5 is begin Mac5 is running Mac6 is begin Mac7 is begin Mac8 is begin Mac9 is begin Mac10 is begin Mac1 end Mac10 is running Mac2 end Mac6 is running Mac3 end Mac9 is running Mac4 end Mac7 is running Mac5 end Mac8 is running Mac10 end Mac9 end Mac7 end Mac6 end Mac8 end the data capture have finished

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpjwsg.html