Java类锁和对象锁实践

来源:互联网 发布:sql*plus命令 编辑:程序博客网 时间:2024/06/05 05:02

类锁和对象锁是否会冲突?对象锁和私有锁是否会冲突?通过实例来进行说明。

一、相关约定

为了明确后文的描述,先对本文涉及到的锁的相关定义作如下约定:

1. 类锁:在代码中的方法上加了static和synchronized的锁,或者synchronized(xxx.class)的代码段,如下文中的increament();

2.对象锁:在代码中的方法上加了synchronized的锁,或者synchronized(this)的代码段,如下文中的synOnMethod()和synInMethod();

3.私有锁:在类内部声明一个私有属性如private Object lock,在需要加锁的代码段synchronized(lock),如下文中的synMethodWithObj()。

二、测试代码

1.编写一个启动类ObjectLock

?
1
2
3
4
5
6
7
8
9
10
publicclass ObjectLock {
    publicstatic void main(String[] args) {
        System.out.println("start time = " + System.currentTimeMillis()+"ms");
        LockTestClass test = newLockTestClass();
        for(inti = 0; i < 3; i++) {
            Thread thread = newObjThread(test, i);
            thread.start();
        }
    }
}

2.编写一个线程类ObjThread,用于启动同步方法(注意它的run方法可能会调整以进行不同的测试)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
publicclass ObjThread extendsThread {
    LockTestClass lock;
    inti = 0;
 
    publicObjThread(LockTestClass lock, inti) {
        this.lock = lock;
        this.i = i;
    }
 
    publicvoid run() {
        //无锁方法
//      lock.noSynMethod(this.getId(),this);
        //对象锁方法1,采用synchronized synInMethod的方式
        lock.synInMethod();
        //对象锁方法2,采用synchronized(this)的方式
//      lock.synOnMethod();
        //私有锁方法,采用synchronized(object)的方式
//      lock.synMethodWithObj();
        //类锁方法,采用static synchronized increment的方式
        LockTestClass.increment();
    }
}

3.再编写一个锁的测试类LockTestClass,包括各种加锁方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
publicclass LockTestClass {
    //用于类锁计数
    privatestatic int i = 0;
    //私有锁
    privateObject object = newObject();
 
    /**
     * &lt;p&gt;
     * 无锁方法
     *
     * @param threadID
     * @param thread
     */
    publicvoid noSynMethod(longthreadID, ObjThread thread) {
        System.out.println("nosyn: class obj is " + thread + ", threadId is"
                + threadID);
    }
 
    /**
     * 对象锁方法1
     */
    publicsynchronized void synOnMethod() {
        System.out.println("synOnMethod begins" ", time = "
                + System.currentTimeMillis() + "ms");
        try{
            Thread.sleep(2000L);
        catch(InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("synOnMethod ends");
    }
 
    /**
     * 对象锁方法2,采用synchronized (this)来加锁
     */
    publicvoid synInMethod() {
        synchronized(this) {
            System.out.println("synInMethod begins" ", time = "
                    + System.currentTimeMillis() + "ms");
            try{
                Thread.sleep(2000L);
            catch(InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("synInMethod ends");
        }
 
    }
 
    /**
     * 对象锁方法3
     */
    publicvoid synMethodWithObj() {
        synchronized(object) {
            System.out.println("synMethodWithObj begins" ", time = "
                    + System.currentTimeMillis() + "ms");
            try{
                Thread.sleep(2000L);
            catch(InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("synMethodWithObj ends");
        }
    }
 
    /**
     * 类锁
     */
    publicstatic synchronized void increament() {
        System.out.println("class synchronized. i = " + i + ", time = "
                + System.currentTimeMillis() + "ms");
        i++;
        try{
            Thread.sleep(2000L);
        catch(InterruptedException e) {
            e.printStackTrace();
        }
         System.out.println("class synchronized ends.");
    }
 
}

三、测试结果

1.测试类锁和对象锁,ObjectThread的run方法修改如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
publicvoid run() {
        //无锁方法
//      lock.noSynMethod(this.getId(),this);
        //对象锁方法1,采用synchronized synInMethod的方式
        lock.synInMethod();
        //对象锁方法2,采用synchronized(this)的方式
//      lock.synOnMethod();
        //私有锁方法,采用synchronized(object)的方式
//      lock.synMethodWithObj();
        //类锁方法,采用static synchronized increment的方式
        LockTestClass.increament();
    }

终端输出:

start time = 1413101360231mssynInMethod begins, time = 1413101360233mssynInMethod endsclass synchronized. i = 0, time = 1413101362233mssynInMethod begins, time = 1413101362233msclass synchronized ends.synInMethod endsclass synchronized. i = 1, time = 1413101364233mssynInMethod begins, time = 1413101364233msclass synchronized ends.synInMethod endsclass synchronized. i = 2, time = 1413101366234msclass synchronized ends.

可以看到对象锁方法(synInMothod)第一次启动时比类锁方法(increament)快2秒,这是因为在synInMehtod执行时sleep了2秒再执行的increament,而这两个方法共用一个线程,所以会慢2秒,如果increament在run中放到synInMethod前面,那么第一次启动时就是increament快2秒。
而当类锁方法启动时,另一个线程时的对象锁方法也几乎同时启动,说明二者使用的并非同一个锁,不会产生竞争。
结论:类锁和对象锁不会产生竞争,二者的加锁方法不会相互影响。

2.私有锁和对象锁,ObjectThread的run方法修改如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
publicvoid run() {
        //无锁方法
//      lock.noSynMethod(this.getId(),this);
        //对象锁方法1,采用synchronized synInMethod的方式
        lock.synInMethod();
        //对象锁方法2,采用synchronized(this)的方式
//      lock.synOnMethod();
        //私有锁方法,采用synchronized(object)的方式
        lock.synMethodWithObj();
        //类锁方法,采用static synchronized increment的方式
//      LockTestClass.increament();
    }

终端输出:

start time = 1413121912406mssynInMethod begins, time = 1413121912407ms.synInMethod ends.synMethodWithObj begins, time = 1413121914407mssynInMethod begins, time = 1413121914407ms.synInMethod ends.synMethodWithObj endssynInMethod begins, time = 1413121916407ms.synMethodWithObj begins, time = 1413121916407mssynInMethod ends.synMethodWithObj endssynMethodWithObj begins, time = 1413121918407mssynMethodWithObj ends

和类锁和对象锁非常类似。

结论:私有锁和对象锁也不会产生竞争,二者的加锁方法不会相互影响。

3.synchronized直接加在方法上和synchronized(this)ObjectThread的run方法修改如下:
public void run() {//无锁方法//lock.noSynMethod(this.getId(),this);//对象锁方法1,采用synchronized synInMethod的方式lock.synInMethod();//对象锁方法2,采用synchronized(this)的方式lock.synOnMethod();//私有锁方法,采用synchronized(object)的方式//lock.synMethodWithObj();//类锁方法,采用static synchronized increment的方式//LockTestClass.increament();}

终端输出:

start time = 1413102913278mssynInMethod begins, time = 1413102913279mssynInMethod endssynInMethod begins, time = 1413102915279mssynInMethod endssynOnMethod begins, time = 1413102917279mssynOnMethod endssynInMethod begins, time = 1413102919279mssynInMethod endssynOnMethod begins, time = 1413102921279mssynOnMethod endssynOnMethod begins, time = 1413102923279mssynOnMethod ends

可以看到,二者严格地串行输出(当然再次执行时先运行synInMethod还是先运行synOnMethod并不是确定的,取决于谁获得了锁)。

结论:synchronized直接加在方法上和synchronized(this)都是对当前对象加锁,二者的加锁方法够成了竞争关系,同一时刻只能有一个方法能执行。

四、参考资料:

  • 类锁与对象锁加锁 synchronized 小解
0 0
原创粉丝点击