售票问题
一、初始代码如下:
public class Thread02{public static void main(String[] args){SellTicket s1 = new SellTicket();SellTicket s2 = new SellTicket();SellTicket s3 = new SellTicket();s1.start();s2.start();s3.start();}
}class SellTicket extends Thread{private static int num = 100;@Overridepublic void run(){while(true){if(num <= 0){break;//end}try{Thread.sleep(50)}catch(InterruptedException e){e.printStackTrace();}num --;System.out.println("Sell A Ticket");}}
}
- 结果出现问题如下:出现剩余票数为负数的情况(前面操作的线程还未来得及对num进行操作时,后面的线程就进行判断并操作)
二、使用Runnable进行多线程操作:
public class Thread02{public static void main(String[] args){SellTicket s1 = new SellTicket();new Thread(s1).start();new Thread(s1).start();new Thread(s1).start();}
}class SellTicket implements Runnable{private int num = 100;@Overridepublic void run(){while(true){if(num <= 0){break;//end}try{Thread.sleep(50)}catch(InterruptedException e){e.printStackTrace();}num --;System.out.println("Sell A Ticket");}}
}