关于线程中使用两种循环的差异
public class ThreadSellTicketDemo implements Runnable{
private int ticket = 100;
public void run(){
sellTicket();
}
void sellTicket(){
// while(true){
// if(ticket > 0){
// System.out.println(Thread.currentThread().getName() + "...onSale..." + ticket--);
// }else{
// break;
// }
// }
for(int i = 0; i< ticket; ticket--){
System.out.println(Thread.currentThread().getName() + "...onSale..." + ticket);
}
}
}
public class UseThreadSellTicketDemo {
public static void main(String[] args) {
ThreadSellTicketDemo tstd1 = new ThreadSellTicketDemo();
Thread t1 = new Thread(tstd1);
Thread t2 = new Thread(tstd1);
Thread t3 = new Thread(tstd1);
Thread t4 = new Thread(tstd1);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
我想问的是,为什么在ThreadSellTicketDemo类中,用while循环可以正常反映100条数据,而如果用for循环总会多出3条数据?因为我开了4个自定义线程,当然main线程除外,另外3个线程总会每个线程多执行一次,结果是103条数据,我不明白,因为我也debug过了,但debug好像和直接运行的结果不同,可能是因为我debug了,所以给CPU的执行线程提供了更多的时间的缘故。如果此处用for循环替代while循环的话,又该如何写呢,请高手指教!