synchronize

synchronize入门

/*
抢票场景
 **/
public class T {
    private int ticktNum = 10;

    // @SneakyThrows
    public void getTickt() throws Exception {
        synchronized (T.class) {
            if (ticktNum <= 0) {
                return;
            }
            Thread.sleep(200);
            System.out.println(Thread.currentThread().getName() +
                    "抢到" + ticktNum);
            ticktNum--;
        }
    }

    public static void main(String[] args) {
        T t = new T();
        for (int i = 1; i <= 20; i++) {
            new Thread(() -> {
                try {
                    t.getTickt();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
posted @ 2024-08-14 14:57  干饭达人GoodLucy  阅读(7)  评论(0编辑  收藏  举报