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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

©   /  2014-6-8 10:18  /  2613 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

下面通过卖票的代码给楼主解析吧。。。

class DemoTecket implements Runnable
{
        private int ticket = 100;
        Object obj = new Object();
        boolean flag = true;

        public void run()
        {
                if(flag)
                {
                        while(true)
                        {
                                synchronized(this)//因为run方法调用的show()方法,show方法调用的是this.所以这里是this
                                {
                                        if(ticket>0)
                                        {
                                                try{Thread.sleep(10);}catch(Exception e){}
                                                System.out.println(Thread.currentThread().getName()+"...同步售票:"+ticket--);
                                        }
                                }
                        }
                }
                else
                {
                        while(true)
                        {
                                show();
                        }
                }
        }

                public synchronized void show()
                {
                        if(ticket>0)
                        {
                                try{Thread.sleep(10);}catch(Exception e){}
                                System.out.println(Thread.currentThread().getName()+"...函数售票:"+ticket--);
                        }
                }
       
       
}
public class 同步函数的锁是this {
       
        public static void main(String[]args)
        {
                DemoTecket dt = new DemoTecket();
               
                Thread t1 = new Thread(dt);
                Thread t2 = new Thread(dt);
                Thread t3 = new Thread(dt);
                Thread t4 = new Thread(dt);
                t1.start();
               
               
                //重点:先让主线程停止10毫秒,当程序执行到t2后,执行一会儿,主线程突然醒了,然后执行主线程
                //原因是,main主函数线程会瞬间将两个线程开启执行,
                //所以当线程执行到t.falg=false时,会直接执行到show方法
                try{Thread.sleep(10);}catch(Exception e){}
                dt.flag=false;
                t2.start();               
        }

}
希望对你有帮助。。。。

评分

参与人数 1技术分 +1 收起 理由
李小然 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马