Balking (犹豫)模式用在一个线程发现另一个线程或本线程已经做了某一件相同的事,那么本线程就无需再做了,直接结束返回。

    1. public class MonitorService {
    2. // 用来表示是否已经有线程已经在执行启动了
    3. private volatile boolean starting;
    4. public void start() {
    5. log.info("尝试启动监控线程...");
    6. synchronized (this) {
    7. if (starting) {
    8. return;
    9. }
    10. starting = true;
    11. }
    12. // 真正启动监控线程...
    13. }
    14. }

    用于实现线程安全的单例

    1. public final class Singleton {
    2. private Singleton() {
    3. }
    4. private static Singleton INSTANCE = null;
    5. public static synchronized Singleton getInstance() {
    6. if (INSTANCE != null) {
    7. return INSTANCE;
    8. }
    9. INSTANCE = new Singleton();
    10. return INSTANCE;
    11. }
    12. }