一.同步模式之保护性暂停
二.异步模式之生产者/消费者
三.线程安全单例
四.享元模式
五.同步模式之Balking
六.终止模式之两阶段终止模式
优化:
七.同步模式之顺序控制
1 固定运行顺序
先打印“t2”,再打印“t1”
1.1 wait/notify
@Slf4j(topic = "c.Test25")
public class Test25 {
final static Object lock = new Object();
//标识t2是否运行过
static boolean t2runned = false;
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
synchronized (lock){
while (!t2runned){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.debug("1");
}
}, "t1");
Thread t2 = new Thread(() -> {
synchronized (lock){
log.debug("2");
t2runned = true;
lock.notify();
}
}, "t2");
t1.start();
t2.start();
}
}
1.2 park/unpark
@Slf4j(topic = "c.Test26")
public class Test26 {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
LockSupport.park();
log.debug("1");
}, "t1");
Thread t2 = new Thread(() -> {
log.debug("2");
LockSupport.unpark(t1);
}, "t2");
t1.start();
t2.start();
}
}
2 交替输出
线程1输出a 5次,线程2输出b 5次,线程3 输出c 5次。现在要求输出abcabcabcabcabc怎么实现
2.1 wait/notify
2.2 await/signal
2.3 park/unpark