java线程同步synchronized问题?
publicclassBuyTicketThreadimplementsRunnable{privateIntegerticket=newInteger(20);priv...
public class BuyTicketThread implements Runnable {
private Integer ticket = new Integer(20);
private boolean flag = true;
public void run() {
while (flag) {
buy();
}
}
public void buy() {
synchronized (ticket) {
if (ticket <= 0) {
flag = false;
System.out.println("票已经全部售完");
return;
}
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "拿到了第" + ticket-- + "张票");
}
}
public static void main(String[] args) {
/*
下面这种声明方式是:
多个线程作用于同对象
*/
BuyTicketThread thread = new BuyTicketThread();
new Thread(thread, "小明").start();
new Thread(thread, "小李").start();
new Thread(thread, "小孙").start();
}
}
为什么这个对象锁还会发送多线程安全问题呀?
代码如下,为什么这个对象锁还会发送 展开
private Integer ticket = new Integer(20);
private boolean flag = true;
public void run() {
while (flag) {
buy();
}
}
public void buy() {
synchronized (ticket) {
if (ticket <= 0) {
flag = false;
System.out.println("票已经全部售完");
return;
}
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "拿到了第" + ticket-- + "张票");
}
}
public static void main(String[] args) {
/*
下面这种声明方式是:
多个线程作用于同对象
*/
BuyTicketThread thread = new BuyTicketThread();
new Thread(thread, "小明").start();
new Thread(thread, "小李").start();
new Thread(thread, "小孙").start();
}
}
为什么这个对象锁还会发送多线程安全问题呀?
代码如下,为什么这个对象锁还会发送 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询