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();
}
}
}