黑马程序员技术交流社区

标题: 有关同步的问题 [打印本页]

作者: 张龙欢    时间: 2013-5-18 17:00
标题: 有关同步的问题
本帖最后由 张龙欢 于 2013-5-21 00:04 编辑

这两个方法同步吗,如果不同步麻烦解释下谢谢!
class Test
{
synchronized static void sayHello3()
{
}
synchronized void getX(){}
}

作者: 黑马华    时间: 2013-5-18 17:10
不同步,因为不是同一把锁,静态函数用的锁是本类字节码文件对象,而非静态类用的是this对象,所以不同步的。
作者: 赵利斌    时间: 2013-5-18 18:28
不同步,静态同步函数的锁是    类名.class        ,同步函数的锁是    this。想要让两个函数同步就需要指定相同的锁。如下代码可以实现同步,而且是安全的。
         
class Demo
{
    public static void main(String[] agre)
    {
            Ticket t=new Ticket();
            Thread t1 = new Thread(t);
                Thread t2 = new Thread(t);
                t1.start();
                try{Thread.sleep(10);}catch(Exception e){}
                t.flag = false;
                t2.start();
    }
}
class Ticket implements Runnable
{
        private static  int tick = 100;
        boolean flag = true;
        public  void run()
        {
                if(flag)
                {
                        while(true)
                        {
                                synchronized(Ticket.class)      //类名.class
                                {
                                        if(tick>0)
                                        {
                                                try{Thread.sleep(10);}catch(Exception e){}
                                                System.out.println(Thread.currentThread().getName()+"....code : "+ tick--);
                                        }
                                }
                        }
                }
                else
                        while(true)
                                show();
        }
        public static synchronized void show()
        {
                if(tick>0)
                {
                        try{Thread.sleep(10);}catch(Exception e){}
                        System.out.println(Thread.currentThread().getName()+"....show.... : "+ tick--);
                }
        }
}

作者: 曹睿翔    时间: 2013-5-19 07:41
如果问题已解决请再次编辑,改为以解决,方便大家看帖




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2