- package cm.nti56;
- public class TicketDemo
- {
- public static void main(String[] args)
- {
- Ticket t = new Ticket();//创建票的对象
- /* Thread t1 = new Thread(t);//创建线程,并把Runnable接口的子类对象传递给Thread的子类对象
- Thread t2 = new Thread(t);
- Thread t3 = new Thread(t);
- t1.start();//开启线程
- t2.start();
- t3.start();*/
- //开启线程
- new Thread(t).start();
- new Thread(t).start();
- new Thread(t).start();
- }
- }
- class Ticket implements Runnable//实现Runnable接口
- {
- private int num = 100;
- //创建同步锁,要在while循环前创建不然会创建很多不同的实例对象,那样就是多个锁了。
- Object obj = new Object();
- public void run()//复写run方法,把需要被多线程执行的代码写入run方法中
- {
- while(true)
- {
- synchronized(obj)
- {
- if(num>0)
- {
- try{Thread.sleep(10);}
- catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"...ticket sale..."+num--);
- } }
- }
- }
- }
复制代码 |