使用extends Thread这种方式,把火车票Ticket单独封装成一个对象,作为共享数据,也可以,以下是代码:- class SellTicket extends Thread
- {
- public SellTicket(Ticket ticket)
- {
- this.ticket = ticket;
- }
- private Ticket ticket;
- @Override
- public void run()
- {
- while(true)
- ticket.printTicket();
- }
-
- }
- class Ticket
- {
- private int count = 100;
- synchronized void printTicket()
- {
- try{Thread.sleep(20);}catch(InterruptedException e){}
- if(count>0)
- System.out.println(Thread.currentThread().getName()+"..."+count--);
- }
- }
- class ThreadTest
- {
- public static void main(String[] args)
- {
- Ticket t = new Ticket();
- new SellTicket(t).start();
- new SellTicket(t).start();
- }
- }
复制代码 |