- //定义Ticket1类实现runnable接口
- class Ticket1 implements Runnable
- {
- private int ticket=10;
- //Object lock=new Object();
- public void run()
- {
- while(true)
- {
- saleTicket();//调用售票方法
- if(ticket<=0)
- {
- break;
- }
- }
- }
- //定义一个同步方法saleTicket
- private synchronized void saleTicket()
- {
- if(ticket>0)
- {
- try
- {
- Thread.sleep(10);//经过此线程的时候休眠10毫秒
- }
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName()+"----卖出的票:"+ticket--);
- }
- }
- }
- class Example12
- {
- public static void main(String[] args)
- {
- Ticket1 t1=new Ticket1();//创建Ticket1对象
- //创建并开启四个线程
- new Thread(t1,"线程一").start();
- new Thread(t1,"线程二").start();
- new Thread(t1,"线程三").start();
- new Thread(t1,"线程四").start();
- //System.out.println("Hello World!");
- }
- }
复制代码
控制台只打印了线程一,1到10的结果。
为什么没有打印出来别的线程呢?
|