购票问题
public class Thread01 {
public static void main(String[] args) {
Ticket01 ticket = new Ticket01();
new Thread(()->ticket.sale(), "A").start();
new Thread(()->ticket.sale(), "B").start();
}
}
class Ticket01 {
int number = 1;
public void sale() {
if (number > 0) {
if (Thread.currentThread().getName().equals("A")) {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
购票解决
public class Thread02 {
public static void main(String[] args) {
Ticket02 ticket = new Ticket02();
new Thread(()->ticket.sale(), "A").start();
new Thread(()->ticket.sale(), "B").start();
}
}
class Ticket02 {
int number = 1;
public synchronized void sale() {
if (number > 0) {
if (Thread.currentThread().getName().equals("A")) {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
领取专属 10元无门槛券
私享最新 技术干货