⽤java ⾃⼰实现代码阻塞的⼏种⽅式
⽤java ⾃⼰实现代码阻塞的⼏种⽅式
假如有⼀个场景,当代码获取的变量不为期待值的时候需要等待变量变为期待值再往下执⾏,最开始可能会考虑通过死循环+线程睡眠来实现,但是这样⼦毕竟不太合理。可以通过以下⽅式来实现:
洋芋酿皮的做法1. 通过阻塞队列。
2. 通过等待唤醒,wait和notify import *;/** 1. ⾃⼰⽤阻塞队列实现代码的阻塞 */public class BlockCode { //创建⼀个线程池 private static ThreadPoolExecutor executor = new ThreadPoolExecutor (5,10,1, TimeUnit .MINUTES ,new LinkedBlockingQueue <>(100)); //创建⼀个容量为1的阻塞队列 private static BlockingQueue <Integer > blockingQueue = new ArrayBlockingQueue <>(1); public static void main (String [] args ) { //吃包⼦ executor .execute (()->{ try { //队列空时获取会阻塞 Integer num = blockingQueue .take (); System .out .println ("成功吃上包⼦"); } catch (InterruptedException e ) { e .printStackTrace (); } }); executor .execute (()->{ try { Thread .sleep (3000); System .out .println ("上架⼀个包⼦"); //队列满了插⼊会阻塞 blockingQueue .put (0); } catch (Exception e ) { e .printStackTrace (); } });
}}
1
2
3
4
5一梦到兵营
6
7
8
9
10
11
12
13
14
15
16
傅雷家书阅读感想
电脑连投影仪17
18
19
20
21
清炖羊肉的家常做法
醋可以洗脸吗22
23
刹车优先系统24
25
26
27
28
29
30
31
32
有你真好英文
33
34
/** * 通过等待唤醒实现阻塞 */public class BlockCode2 { private static ThreadPoolExecutor executor = new ThreadPoolExecutor (5,10,1, TimeUnit .MINUTES ,new LinkedBlockingQueue <>(100)); public static void main (String [] args ) { executor .execute (()->{ //假如从数据库查询出来⼀个包⼦,这⾥不考虑线程安全 String bread = null ; if (bread ==null ){ synchronized ("包⼦"){ try { "包⼦".wait (); } catch (InterruptedException e ) { e .printStackTrace (); } } System .out .println ("成功吃上包⼦"); } }); executor .execute (()->{ try { //做包⼦时间 Thread .sleep (3000); } catch (InterruptedException e ) { e .printStackTrace (); } //假如⽣产了⼀个包⼦并且放⼊了数据库了 System .out .println ("上架⼀个包⼦"); synchronized ("包⼦"){ //唤醒所有等待的线程 "包⼦".notifyAll (); } }); }}12345678910111213141516171819202122232425262728293031323334353637