BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / java / #34958同步于 2014/9/26
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖

请教一个线程同步问题,麻烦大家帮忙看一下

wei866
2014/9/26镜像同步5 回复
class SellTickets implements Runnable { private Tickets t = new Tickets(); public void run() { while(t.tickets > 0) { try{ Thread.sleep(50); } catch(InterruptedException e) { e.printStackTrace(); } t.sell(); } } } class Tickets { int tickets = 20; public synchronized void sell() { System.out.println(Thread.currentThread().getName() + " is selling tickets " + tickets--); } } public class SellTicketsTester { public static void main(String[] args) { SellTickets st = new SellTickets(); new Thread(st).start(); new Thread(st).start(); new Thread(st).start(); } } 循环时判断语句是tickets>0, 为什么会输出0和1呢? Thread-1 is selling tickets 20 Thread-0 is selling tickets 19 Thread-2 is selling tickets 18 Thread-1 is selling tickets 17 Thread-0 is selling tickets 16 Thread-2 is selling tickets 15 Thread-1 is selling tickets 14 Thread-0 is selling tickets 13 Thread-2 is selling tickets 12 Thread-1 is selling tickets 11 Thread-0 is selling tickets 10 Thread-2 is selling tickets 9 Thread-1 is selling tickets 8 Thread-2 is selling tickets 7 Thread-0 is selling tickets 6 Thread-1 is selling tickets 5 Thread-2 is selling tickets 4 Thread-0 is selling tickets 3 Thread-1 is selling tickets 2 Thread-2 is selling tickets 1 Thread-0 is selling tickets 0 Thread-1 is selling tickets -1
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
taoch机器人#1 · 2014/9/26
假设在某一时刻,Tickets.tickets为1 在这一时刻,三个线程同时执行到while(t.tickets>0)那句 于是都能够满足,就都进入到这次循环中,于是 分别输出了1、0、-1 【 在 wei866 (wei866) 的大作中提到: 】 : class SellTickets implements Runnable { : private Tickets t = new Tickets(); : public void run() { : ...................
wei866机器人#2 · 2014/9/26
谢谢,就是说在判断之前就应该加锁是吗? 【 在 taoch 的大作中提到: 】 : 假设在某一时刻,Tickets.tickets为1 : 在这一时刻,三个线程同时执行到while(t.tickets>0)那句 : 于是都能够满足,就都进入到这次循环中,于是 分别输出了1、0、-1 : ...................
taoch机器人#3 · 2014/9/26
可以的 【 在 wei866 (wei866) 的大作中提到: 】 : 谢谢,就是说在判断之前就应该加锁是吗?
wei866机器人#4 · 2014/9/26
谢谢 【 在 taoch 的大作中提到: 】 : 可以的 :
ab机器人#5 · 2014/10/2
把判断语句也放在sell方法里就好了 【 在 wei866 的大作中提到: 】 class SellTickets implement...