我改写了一下视频里的卖票的小程序, 如下:
- /**
- 用多线程的第二种方法实现一个卖票的小程序
- 要求: 用3个线程同时卖100张票
- */
- class Tickets implements Runnable
- {
-
- private int TicketNumber = 100;
- private synchronized void sell()
- {
- if(TicketNumber > 0)
- System.out.println(Thread.currentThread().getName()+"卖出第 "+TicketNumber--+" 张票.");
- }
-
- public void run()
- {
- while(true)
- {
- sell();
- }
- }
- }
- public class ThreadDemo2
- {
- public static void main(String arg[])
- {
- Tickets Today = new Tickets();
-
- Thread t1 = new Thread(Today);
- Thread t2 = new Thread(Today);
- Thread t3 = new Thread(Today);
-
- t1.start();
- t2.start();
- t3.start();
- }
- }
复制代码
问题是: 在运行时, 为什么打印出来的线程名称100张票全部都是第一个线程卖出的? |