关于线程中使用两种循环的差异

u010021183 2014-11-05 11:06:12
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循环的话,又该如何写呢,请高手指教!
...全文
195 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
cjh_tostring 2014-11-06
  • 打赏
  • 举报
回复
你这个不应该是关while或者for循环的原因,while可能也会出问题的。 你的四个线程都有用到ticket 这个变量,假设有一个线程分配到cpu执行,刚执行到for循环的i< ticket;这个判断或者while的 if(ticket > 0)这个判断,这时候这个线程分配的时间到了,有另外的线程执行,这两个线程用到的ticket这给变量的值是一样的就会,就会出现循环次数大于100的情况。 你需要对你的sellTicket这个方法做出保护,你可以改方法加上synchronized关键字来保护。

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧