java多线程系列04-----synchronized关键字

1synchronized原理

在java中每一个对象有且仅有一个同步锁,这也意味着同步锁是依赖对象而存在。

当我们在调用对象的synchronized方法时,就获取了该对象的同步锁,例如synchronized(obj)就获取了"obj这个对象"的同步锁

不同线程对同步锁的访问是互斥的,也就是说,在某个时间点,对象的同步锁只能被一个线程获取到!通过同步锁,我们可以实现对对象/方法的互斥访问。

例如现在有两个线程A B他们都会访问对象的同步锁,在某一时刻,线程A获得对象的同步锁,并进行一些操作,而此时线程B也企图获取对象的同步锁,线程B这个操作就会失败,他必须等待,等到线程A释放了这个对象的同步锁,他才可以执行。

2synchronized基本规则

synchronized的规则基本有下面三条

第一条:当一个线程访问某个对象的synchronized方法或者代码块,其他线程对该对象的访问将会被阻塞。

第二条:当一个线程访问 某对象的synchronized方法或者代码块时候,其他线程仍然可以访问该独享的非同步代码块。

第三条:当一个线程访问某个对象的synchronized方法或者代码块时候,其他线程对该对象的其他的synchronized方法或者代码块的访问将被阻塞

第一条 代码演示模块

package com.tuhu.filt.javadata;

public class MyRunable implements Runnable {
    @Override
    public void run() {
        synchronized (this){
            for (int i = 0;i < 5;i++){
                try {
                    Thread.sleep(100);
                    System.out.println(
                            Thread.currentThread().getName()
                            +"loop"
                    );
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
class Demo_1{
    public static void main(String[] args) {
        Runnable demo = new MyRunable();
        Thread t1 = new Thread(demo,"t1");
        Thread t2 = new Thread(demo,"t2");
        t1.start();
        t2.start();
    }
}

run()方法中存在"synchronized(this)"代码块,而且t1和t2都是基于"demo这个Runnable"对象创建的线程,这就意味着,我们可以将synchronized(this)中的this看作是"demo这个Runnable对象";因此,线程1和线程2共享demo对象的同步锁,所以当一个线程运行的时候,另外一个线程必须等待"运行线程"释放"demo"的同步锁之后才能运行

下面我们将代码稍微修改一下,再来看看运行结果是怎么样的

package com.tuhu.filt.javadata;

public class MyRunable implements Runnable {
    @Override
    public void run() {
        synchronized (this){
            for (int i = 0;i < 5;i++){
                try {
                    Thread.sleep(100);
                    System.out.println(
                            Thread.currentThread().getName()
                            +"loop"
                    );
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
class Demo_1{
    public static void main(String[] args) {
        Runnable demo = new MyRunable();
        Thread t1 = new Thread(demo,"t1");
        Thread t2 = new Thread(demo,"t2");
        t1.start();
        t2.start();
    }
}
class MyThread2 extends Thread{
    public MyThread2(String name){
        super(name);
    }
    @Override
    public void run(){
        synchronized (this){
            for(int i = 0;i<5;i++){
                try {
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName()
                            +"loop");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
class Demo_2{
    public static void main(String[] args) {
        Thread t1 = new MyThread2("t1");
        Thread t2 = new MyThread2("t2");

        t1.start();
        t2.start();
    }
}

比较Demo1和Demo2 我们发现 Demo2中的MyThread类是直接继承于Thread,而且t1和t2都是直接继承于MyThread子线程,幸运的是 在Demo2中也调用了synchronized(this),正如Demo1中的run方法,也调用了synchronized(this)一样,但是正如我们看到的结果一样这里的接过不是我们预期的那种将t2阻塞住,这里的synchronized(this)代表的是MyThread对象,而t1和t2是两个不同的MyThread对象,因此t1和t2在执行synchronized(this)时,获取的是不同对象的同步锁,对于Demo1而言,synchronized(this)中的this代表的是MyRunable对象;t1和t2共同一个MyRunable对象,因此一个对象获得了同步锁,会造成另一个线程的等待。

第二条的代码演示(当一个线程访问该对象的synchronized方法或者代码块的时候,其他线程仍然可以访问该对象的非同步代码块)

下面是synchronized代码块的演示程序

package com.tuhu.filt.javadata;

class Count{
    /**
     * synMethod()是一个同步块方法
     */
    public void synMethod(){
        synchronized (this){
                try {
                    for (int i =0;i<5;i++){
                        Thread.sleep(100);
                        System.out.println(Thread.currentThread().getName()
                                +"synMethod loop"+i);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }
    }
    /**
     * 非同步方法nonSynMethod()
     */
    public void nonSynMethod(){
            try {
                for(int i = 0;i<5;i++) {
                    Thread.sleep(100);
                    System.out.println(
                            Thread.currentThread().getName()
                            +"synMethod loop"+i
                    );
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
}
public class Demo2 {
    public static void main(String[] args) {
        final Count count = new Count();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                count.synMethod();
            }
        },"t1");
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                count.nonSynMethod();;
            }
        },"t2");
        t1.start();
        t2.start();
        }
}

结果说明

主线程中新建两个子线程t1 和 t2 t1会调用count对象的synMethod()方法,该方法内含有同步块;而t2则会调用,count对象的nonSynMethod()方法,该方法不是同步方法。t1运行时,虽然调用的synchronized(this)获取"count的同步锁";但是并没有造成t2的阻塞,因为t2没有用到"count"同步锁

第三条

当一个线程访问某对象的synchronized方法或者synchronized代码块时,其他线程对该对象的其他synchronized方法将会被阻塞,只需要将上面的nonSynMethod()方法体也用synchronized(this)修饰。

代码如下

package com.tuhu.filt.javadata;

class Count{
    /**
     * synMethod()是一个同步块方法
     */
    public void synMethod(){
        synchronized (this){
                try {
                    for (int i =0;i<5;i++){
                        Thread.sleep(100);
                        System.out.println(Thread.currentThread().getName()
                                +"synMethod loop"+i);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }
    }
    /**
     * 非同步方法nonSynMethod()
     */
    public void nonSynMethod(){
        synchronized (this){
            try {
                for(int i = 0;i<5;i++) {
                    Thread.sleep(100);
                    System.out.println(
                            Thread.currentThread().getName()
                                    +"synMethod loop"+i
                    );
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        }
}
public class Demo2 {
    public static void main(String[] args) {
        final Count count = new Count();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                count.synMethod();
            }
        },"t1");
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                count.nonSynMethod();;
            }
        },"t2");
        t1.start();
        t2.start();
        }
}

 结果说明

主线程中 新建了两个子线程t1和t2 t1 和 t2运行时都调用,synchronized(this),这个this是Count对象(Count),而t1和t2共用count. 因此在t1运行时 t2会被阻塞,t1释放同步锁之后,t2才能运行

3 synchronized方法和synchronized代码块

synchronized方法是用synchronized修饰方法,而synchronized代码块则是用synchronized修饰代码块

synchronized方法示例

public synchronized void foo1(){
        System.out.println("synchronized method");
    }

synchronized代码块

public void foo2(){
        synchronized (this){
            System.out.println("synchronized method");
        }
    }

synchronized代码块中this指的是当前对象,也可以将this替换成obj,则foo2()在执行synchronized(obj)时就获取的是obj的同步锁

synchronized代码块可以更精确的控制冲突限制访问区域,有时候表现的更效率,下面通过一个示例来演示。

下面上代码证明一下

package com.tuhu.filt.javadata;

public class Demo4 {
    public synchronized void synMethod(){
        for(int i = 0;i<1000000;i++){
            ;
        }
    }
    public void synBlock(){
        synchronized (this){
            for(int i =0;i<1000000;i++){
                ;
            }
        }
    }

    public static void main(String[] args) {
        Demo4 demo = new Demo4();
        long start,diff;
        start = System.currentTimeMillis();
        demo.synMethod();
        diff = System.currentTimeMillis() - start;
        System.out.println("synMethod()运行的时间:" + diff);

        start = System.currentTimeMillis();
        demo.synBlock();
        diff = System.currentTimeMillis() - start;
        System.out.println("synBlock()运行的时间:" +diff);
    }
}

(某一次)执行结果

synMethod()运行的时间:5

synBlock()运行的时间:3

4 实例锁 和 全局锁

实例锁:锁在某一个实例对象上,如果该类是单例,那么该锁也具有全局锁的概念,实例锁对应的就是synchronized关键字。

全局锁:该锁针对的是类,无论实例多少个对象,那么线程都共享该锁

全局锁对应的就是static synchronized(或者是锁在该类的class或者classloader对象上)

下面举一个关于 "实例锁"和"全局锁"有一个很形象的例子:

public class Something {
    public synchronized void isSyncA(){}
    public synchronized void isSyncB(){}
    public static synchronized void cSyncA(){}
    public static synchronized void cSyncB(){}
}

假设,Something有两个实例x和y。分析下面4组表达式获取锁的情况

(01) x.isSyncA()与x.isSyncB()
(02) x.isSyncA()与y.isSyncA()
(03) x.cSyncA()与y.cSyncB()
(04) x.isSyncA()与Something.cSyncA()

01 这个在上面synchronized规则中已经讲过了肯定是不能同时使用的,因为他们都是访问同一个对象(对象x)的同步锁!

package com.tuhu.filt.javadata;

public class Something {
    public synchronized void isSyncA(){
        try{
            for(int i = 0;i<5;i++){
                Thread.sleep(100);
                System.out.println(
                        Thread.currentThread().getName()
                        +":isSyncA"
                );
            }
        }catch (InterruptedException ie){

        }
    }
    public synchronized void isSyncB(){
        try{
            for(int i = 0;i<5;i++) {
                Thread.sleep(100);
                System.out.println(
                        Thread.currentThread().getName()
                                + ":isSyncB"
                );
            }
        }catch (InterruptedException ie){

        }
    }
    public static synchronized void cSyncA(){}
    public static synchronized void cSyncB(){}
}
class LockTest1{
    Something x = new Something();
    Something y = new Something();

    private void test1(){
        Thread tl1 = new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        x.isSyncA();
                    }
                }
       ,"tl1" );

        Thread tl2 = new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        x.isSyncB();
                    }
                }
        ,"tl2");
        tl1.start();
        tl2.start();
    }

    public static void main(String[] args) {
        LockTest1 demo = new LockTest1();
        demo.test1();
    }
}

02 可以同时被访问,因为访问的不是同一个对象的同步锁,x.isSyncA()访问的是x的同步锁,而y.isSyncA()访问的是y的同步锁

下面上代码

package com.tuhu.filt.javadata;

public class Something {
    public synchronized void isSyncA(){
        try{
            for(int i = 0;i<5;i++){
                Thread.sleep(100);
                System.out.println(
                        Thread.currentThread().getName()
                        +":isSyncA"
                );
            }
        }catch (InterruptedException ie){

        }
    }
    public synchronized void isSyncB(){
        try{
            for(int i = 0;i<5;i++) {
                Thread.sleep(100);
                System.out.println(
                        Thread.currentThread().getName()
                                + ":isSyncB"
                );
            }
        }catch (InterruptedException ie){

        }
    }
    public static synchronized void cSyncA(){
        try{
            for(int i = 0;i<5;i++) {
                Thread.sleep(100);
                System.out.println(
                        Thread.currentThread().getName()
                                + ":cSyncA"
                );
            }
        }catch (InterruptedException ie){

        }
    }
    public static synchronized void cSyncB(){
        try{
            for(int i = 0;i<5;i++) {
                Thread.sleep(100);
                System.out.println(
                        Thread.currentThread().getName()
                                + ":cSyncB"
                );
            }
        }catch (InterruptedException ie){

        }
    }
}
class LockTest1{
    Something x = new Something();
    Something y = new Something();

    /**
     * 测01的两个,如果一个线程A访问一个对象的synchronized方法
     * 一个线程B去访问同一个对象的synchronized方法就会被阻塞住
     * @param args
     */
//    private void test1(){
//        Thread tl1 = new Thread(
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        x.isSyncA();
//                    }
//                }
//       ,"tl1" );
//
//        Thread tl2 = new Thread(
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        x.isSyncB();
//                    }
//                }
//        ,"tl2");
//        tl1.start();
//        tl2.start();
//    }

    /**
     * 两个线程各自访问不同对象的synchronized方法
     * 是畅通无阻的
     */
    private void test2(){
        Thread t21 = new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        x.isSyncA();
                    }
                }
        ,"t21");

        Thread t22 = new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        y.isSyncA();
                    }
                }
        ,"t22");
        t21.start();
        t22.start();

    }
    public static void main(String[] args) {
        LockTest1 demo = new LockTest1();
        demo.test2();
    }
}

 03 不能被同时访问 因为cSyncA() 和 cSyncB() 都是static 类型的,x.cSynA() 相当于Something.isSynA(),y.cSyncB() 因此他们共用一个同步锁,不能被同时访问

下面上代码

package com.tuhu.filt.javadata;

public class Something {
    public synchronized void isSyncA(){
        try{
            for(int i = 0;i<5;i++){
                Thread.sleep(100);
                System.out.println(
                        Thread.currentThread().getName()
                        +":isSyncA"
                );
            }
        }catch (InterruptedException ie){

        }
    }
    public synchronized void isSyncB(){
        try{
            for(int i = 0;i<5;i++) {
                Thread.sleep(100);
                System.out.println(
                        Thread.currentThread().getName()
                                + ":isSyncB"
                );
            }
        }catch (InterruptedException ie){

        }
    }
    public static synchronized void cSyncA(){
        try{
            for(int i = 0;i<5;i++) {
                Thread.sleep(100);
                System.out.println(
                        Thread.currentThread().getName()
                                + ":cSyncA"
                );
            }
        }catch (InterruptedException ie){

        }
    }
    public static synchronized void cSyncB(){
        try{
            for(int i = 0;i<5;i++) {
                Thread.sleep(100);
                System.out.println(
                        Thread.currentThread().getName()
                                + ":cSyncB"
                );
            }
        }catch (InterruptedException ie){

        }
    }
}
class LockTest1{
    Something x = new Something();
    Something y = new Something();

    /**
     * 测01的两个,如果一个线程A访问一个对象的synchronized方法
     * 一个线程B去访问同一个对象的synchronized方法就会被阻塞住
     * @param args
     */
//    private void test1(){
//        Thread tl1 = new Thread(
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        x.isSyncA();
//                    }
//                }
//       ,"tl1" );
//
//        Thread tl2 = new Thread(
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        x.isSyncB();
//                    }
//                }
//        ,"tl2");
//        tl1.start();
//        tl2.start();
//    }

    /**
     * 两个线程各自访问不同对象的synchronized方法
     * 是畅通无阻的
     */
//    private void test2(){
//        Thread t21 = new Thread(
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        x.isSyncA();
//                    }
//                }
//        ,"t21");
//
//        Thread t22 = new Thread(
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        y.isSyncA();
//                    }
//                }
//        ,"t22");
//        t21.start();
//        t22.start();
//
//    }
    private void test3(){
        Thread t31 = new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        Something.cSyncA();
                    }
                }
        ,"t31");


        Thread t32 = new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        Something.cSyncB();
                    }
                }
                ,"t32");

        t31.start();
        t32.start();
    }
    public static void main(String[] args) {
        LockTest1 demo = new LockTest1();
        demo.test3();
    }
}

04 可以被同时访问 因为isSyncA()是实例方法,x.isSyncA()使用的是对象x的锁;而cSyncA()是静态方法,Something.cSyncA()可以理解对使用的是"类的锁"。 因此他们是可以被同时访问的

下面上代码

package com.tuhu.filt.javadata;

public class Something {
    public synchronized void isSyncA(){
        try{
            for(int i = 0;i<5;i++){
                Thread.sleep(100);
                System.out.println(
                        Thread.currentThread().getName()
                        +":isSyncA"
                );
            }
        }catch (InterruptedException ie){

        }
    }
    public synchronized void isSyncB(){
        try{
            for(int i = 0;i<5;i++) {
                Thread.sleep(100);
                System.out.println(
                        Thread.currentThread().getName()
                                + ":isSyncB"
                );
            }
        }catch (InterruptedException ie){

        }
    }
    public static synchronized void cSyncA(){
        try{
            for(int i = 0;i<5;i++) {
                Thread.sleep(100);
                System.out.println(
                        Thread.currentThread().getName()
                                + ":cSyncA"
                );
            }
        }catch (InterruptedException ie){

        }
    }
    public static synchronized void cSyncB(){
        try{
            for(int i = 0;i<5;i++) {
                Thread.sleep(100);
                System.out.println(
                        Thread.currentThread().getName()
                                + ":cSyncB"
                );
            }
        }catch (InterruptedException ie){

        }
    }
}
class LockTest1{
    Something x = new Something();
    Something y = new Something();

    /**
     * 测01的两个,如果一个线程A访问一个对象的synchronized方法
     * 一个线程B去访问同一个对象的synchronized方法就会被阻塞住
     * @param args
     */
//    private void test1(){
//        Thread tl1 = new Thread(
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        x.isSyncA();
//                    }
//                }
//       ,"tl1" );
//
//        Thread tl2 = new Thread(
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        x.isSyncB();
//                    }
//                }
//        ,"tl2");
//        tl1.start();
//        tl2.start();
//    }

    /**
     * 两个线程各自访问不同对象的synchronized方法
     * 是畅通无阻的
     */
//    private void test2(){
//        Thread t21 = new Thread(
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        x.isSyncA();
//                    }
//                }
//        ,"t21");
//
//        Thread t22 = new Thread(
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        y.isSyncA();
//                    }
//                }
//        ,"t22");
//        t21.start();
//        t22.start();
//
//    }

    /**
     * 都是如遇类的静态方法
     * 我们可以把它理解为类的锁
     * 他们都是类的锁,所以同时访问会产生阻塞
     */
//    private void test3(){
//        Thread t31 = new Thread(
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        Something.cSyncA();
//                    }
//                }
//        ,"t31");
//
//
//        Thread t32 = new Thread(
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        Something.cSyncB();
//                    }
//                }
//                ,"t32");
//
//        t31.start();
//        t32.start();
//    }
    private void test4(){
        Thread t41 = new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        x.isSyncA();
                    }
                }
        );

        Thread t42 = new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        Something.cSyncA();
                    }
                }
        );
        t41.start();;
        t42.start();
    }
    public static void main(String[] args) {
        LockTest1 demo = new LockTest1();
        demo.test4();
    }
}

完结  嘿嘿  lisiming敲于20180804 星期六 17:57 在途虎养车公司

猜你喜欢

转载自blog.csdn.net/lsm18829224913/article/details/81413593