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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

凌风未动

初级黑马

  • 黑马币:

  • 帖子:

  • 精华:

© 凌风未动 初级黑马   /  2016-7-19 09:07  /  339 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

class ThreadDemo2
{
        public static void main(String[] args) throws Exception
        {
                Tick t=new Tick();
                Con1 con1=new Con1(t);
                Con2 con2=new Con2(t);
                Thread t1=new Thread(con1,"消费者1");
                Thread t2=new Thread(con2,"消费者2");
                t1.start();
                t2.start();
        }
}
class Tick
{
        private int tickNum=100;
        private Object obj=new Object();
        int x=0;
        public void sell()
        {
                synchronized(obj)
                {
                        try
                        {
                                if(x%2==0)
                                {
                                        if(tickNum>0)
                                                System.out.println(Thread.currentThread().getName()+":::"+tickNum--);       
                                        x=x+1;
                                }
                               
                        }
                        catch (Exception e)
                        {
                                e.printStackTrace(System.out);
                        }
                       
                }
        }
       
}
class Con1 implements Runnable
{
        Tick t;
        Con1(Tick t)
        {
                this.t=t;
        }
        public void run()
        {
                while(true)       
                {
                        if(t.x%2==0)       
                                t.sell();
                }       
        }


}
class Con2 implements Runnable
{
        Tick t;
        Con2(Tick t)
        {
                this.t=t;
        }
        public void run()
        {
                while(true)
                {
                        if(t.x%2!=0)
                                t.sell();
                }
                       
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马