A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 左华清 黑马帝   /  2012-2-22 16:27  /  1585 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 左华清 于 2012-2-23 11:44 编辑

public class ThreadDemo1 {
        public static void main(String[]args){
                TestThread tt=new TestThread();
                new Thread(tt).start();
                new Thread(tt).start();
        }
}
class TestThread implements Runnable{
        int tickets=100;
        public void run(){
                while(true){
                        if(tickets>0){
                                try{Thread.sleep(1);}catch(Exception e){};
                                System.out.println("run:"+Thread.currentThread().getName()+"-----is sailing ticket"+tickets--);
                        }
                }
        }
}

打印出来的数据出现0
这是什么情况呀

评分

参与人数 1技术分 +1 收起 理由
admin + 1

查看全部评分

4 个回复

倒序浏览
你并没有使用synchronized关键字进行同步,
回复 使用道具 举报
最后几行:
run:Thread-0-----is sailing ticket2
run:Thread-1-----is sailing ticket1
run:Thread-0-----is sailing ticket0
原因是两个线程操作的是同一个tt,同一个tickets。当Thread-0在sleep(1)的时候,Thread-1过来把tickets减成1,所以Thread-0 sleep()后继续执行tickets--就成0了。

评分

参与人数 1技术分 +1 收起 理由
admin + 1

查看全部评分

回复 使用道具 举报
在写多线程的方法时要考虑同步的问题我我觉得
回复 使用道具 举报
谢谢,明白了!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马