当前位置: 移动技术网 > IT编程>开发语言>Java > java基本教程之synchronized关键字 java多线程教程

java基本教程之synchronized关键字 java多线程教程

2019年07月22日  | 移动技术网IT编程  | 我要评论

本章,会对synchronized关键字进行介绍。涉及到的内容包括:
1. synchronized原理
2. synchronized基本规则
3. synchronized方法 和 synchronized代码块
4. 实例锁 和 全局锁

1. synchronized原理

在java中,每一个对象有且仅有一个同步锁。这也意味着,同步锁是依赖于对象而存在。
当我们调用某对象的synchronized方法时,就获取了该对象的同步锁。例如,synchronized(obj)就获取了“obj这个对象”的同步锁。
不同线程对同步锁的访问是互斥的。也就是说,某时间点,对象的同步锁只能被一个线程获取到!通过同步锁,我们就能在多线程中,实现对“对象/方法”的互斥访问。 例如,现在有两个线程a和线程b,它们都会访问“对象obj的同步锁”。假设,在某一时刻,线程a获取到“obj的同步锁”并在执行一些操作;而此时,线程b也企图获取“obj的同步锁” —— 线程b会获取失败,它必须等待,直到线程a释放了“该对象的同步锁”之后线程b才能获取到“obj的同步锁”从而才可以运行。


2. synchronized基本规则

我们将synchronized的基本规则总结为下面3条,并通过实例对它们进行说明。
第一条: 当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程对“该对象”的该“synchronized方法”或者“synchronized代码块”的访问将被阻塞。
第二条: 当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程仍然可以访问“该对象”的非同步代码块。
第三条: 当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程对“该对象”的其他的“synchronized方法”或者“synchronized代码块”的访问将被阻塞。

第一条

当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程对“该对象”的该“synchronized方法”或者“synchronized代码块”的访问将被阻塞。
下面是“synchronized代码块”对应的演示程序。

复制代码 代码如下:

class myrunable implements runnable {

    @override
    public void run() {
        synchronized(this) {
            try { 
                for (int i = 0; i < 5; i++) {
                    thread.sleep(100); // 休眠100ms
                    system.out.println(thread.currentthread().getname() + " loop " + i); 
                }
            } catch (interruptedexception ie) { 
            }
        } 
    }
}

public class demo1_1 {

    public static void main(string[] args) { 
        runnable demo = new myrunable();     // 新建“runnable对象”

        thread t1 = new thread(demo, "t1");  // 新建“线程t1”, t1是基于demo这个runnable对象
        thread t2 = new thread(demo, "t2");  // 新建“线程t2”, t2是基于demo这个runnable对象
        t1.start();                          // 启动“线程t1”
        t2.start();                          // 启动“线程t2”
    }
}

运行结果:

复制代码 代码如下:

t1 loop 0
t1 loop 1
t1 loop 2
t1 loop 3
t1 loop 4
t2 loop 0
t2 loop 1
t2 loop 2
t2 loop 3
t2 loop 4

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

如果你确认,你搞清楚这个问题了。那我们将上面的代码进行修改,然后再运行看看结果怎么样,看看你是否会迷糊。修改后的源码如下:

复制代码 代码如下:

class mythread extends thread {

    public mythread(string name) {
        super(name);
    }

    @override
    public void run() {
        synchronized(this) {
            try { 
                for (int i = 0; i < 5; i++) {
                    thread.sleep(100); // 休眠100ms
                    system.out.println(thread.currentthread().getname() + " loop " + i); 
                }
            } catch (interruptedexception ie) { 
            }
        } 
    }
}

public class demo1_2 {

    public static void main(string[] args) { 
        thread t1 = new mythread("t1");  // 新建“线程t1”
        thread t2 = new mythread("t2");  // 新建“线程t2”
        t1.start();                          // 启动“线程t1”
        t2.start();                          // 启动“线程t2”
    }
}

代码说明:
比较demo1_2 和 demo1_1,我们发现,demo1_2中的mythread类是直接继承于thread,而且t1和t2都是mythread子线程。
幸运的是,在“demo1_2的run()方法”也调用了synchronized(this),正如“demo1_1的run()方法”也调用了synchronized(this)一样!
那么,demo1_2的执行流程是不是和demo1_1一样呢?
运行结果:

复制代码 代码如下:

t1 loop 0
t2 loop 0
t1 loop 1
t2 loop 1
t1 loop 2
t2 loop 2
t1 loop 3
t2 loop 3
t1 loop 4
t2 loop 4

结果说明:
如果这个结果一点也不令你感到惊讶,那么我相信你对synchronized和this的认识已经比较深刻了。否则的话,请继续阅读这里的分析。
synchronized(this)中的this是指“当前的类对象”,即synchronized(this)所在的类对应的当前对象。它的作用是获取“当前对象的同步锁”。
对于demo1_2中,synchronized(this)中的this代表的是mythread对象,而t1和t2是两个不同的mythread对象,因此t1和t2在执行synchronized(this)时,获取的是不同对象的同步锁。对于demo1_1对而言,synchronized(this)中的this代表的是myrunable对象;t1和t2共同一个myrunable对象,因此,一个线程获取了对象的同步锁,会造成另外一个线程等待。

第二条

当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程仍然可以访问“该对象”的非同步代码块。
下面是“synchronized代码块”对应的演示程序。

复制代码 代码如下:

class count {

    // 含有synchronized同步块的方法
    public void synmethod() {
        synchronized(this) {
            try { 
                for (int i = 0; i < 5; i++) {
                    thread.sleep(100); // 休眠100ms
                    system.out.println(thread.currentthread().getname() + " synmethod loop " + i); 
                }
            } catch (interruptedexception ie) { 
            }
        } 
    }

    // 非同步的方法
    public void nonsynmethod() {
        try { 
            for (int i = 0; i < 5; i++) {
                thread.sleep(100);
                system.out.println(thread.currentthread().getname() + " nonsynmethod loop " + i); 
            }
        } catch (interruptedexception ie) { 
        }
    }
}

public class demo2 {

    public static void main(string[] args) { 
        final count count = new count();
        // 新建t1, t1会调用“count对象”的synmethod()方法
        thread t1 = new thread(
                new runnable() {
                    @override
                    public void run() {
                        count.synmethod();
                    }
                }, "t1");

        // 新建t2, t2会调用“count对象”的nonsynmethod()方法
        thread t2 = new thread(
                new runnable() {
                    @override
                    public void run() {
                        count.nonsynmethod();
                    }
                }, "t2"); 


        t1.start();  // 启动t1
        t2.start();  // 启动t2
    }
}

运行结果:

复制代码 代码如下:

t1 synmethod loop 0
t2 nonsynmethod loop 0
t1 synmethod loop 1
t2 nonsynmethod loop 1
t1 synmethod loop 2
t2 nonsynmethod loop 2
t1 synmethod loop 3
t2 nonsynmethod loop 3
t1 synmethod loop 4
t2 nonsynmethod loop 4

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

第三条

当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程对“该对象”的其他的“synchronized方法”或者“synchronized代码块”的访问将被阻塞。
我们将上面的例子中的nonsynmethod()方法体的也用synchronized(this)修饰。修改后的源码如下:

复制代码 代码如下:

class count {

    // 含有synchronized同步块的方法
    public void synmethod() {
        synchronized(this) {
            try { 
                for (int i = 0; i < 5; i++) {
                    thread.sleep(100); // 休眠100ms
                    system.out.println(thread.currentthread().getname() + " synmethod loop " + i); 
                }
            } catch (interruptedexception ie) { 
            }
        } 
    }

    // 也包含synchronized同步块的方法
    public void nonsynmethod() {
        synchronized(this) {
            try { 
                for (int i = 0; i < 5; i++) {
                    thread.sleep(100);
                    system.out.println(thread.currentthread().getname() + " nonsynmethod loop " + i); 
                }
            } catch (interruptedexception ie) { 
            }
        }
    }
}

public class demo3 {

    public static void main(string[] args) { 
        final count count = new count();
        // 新建t1, t1会调用“count对象”的synmethod()方法
        thread t1 = new thread(
                new runnable() {
                    @override
                    public void run() {
                        count.synmethod();
                    }
                }, "t1");

        // 新建t2, t2会调用“count对象”的nonsynmethod()方法
        thread t2 = new thread(
                new runnable() {
                    @override
                    public void run() {
                        count.nonsynmethod();
                    }
                }, "t2"); 


        t1.start();  // 启动t1
        t2.start();  // 启动t2
    }
}

(某一次)执行结果:

复制代码 代码如下:

synmethod() : 11
synblock() : 3
 

4. 实例锁 和 全局锁
实例锁 -- 锁在某一个实例对象上。如果该类是单例,那么该锁也具有全局锁的概念。
实例锁对应的就是synchronized关键字。
全局锁 -- 该锁针对的是类,无论实例多少个对象,那么线程都共享该锁。
全局锁对应的就是static synchronized(或者是锁在该类的class或者classloader对象上)。

关于“实例锁”和“全局锁”有一个很形象的例子:

复制代码 代码如下:

pulbic 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) 不能被同时访问。因为issynca()和issyncb()都是访问同一个对象(对象x)的同步锁!

复制代码 代码如下:

// locktest2.java的源码
class something {
    public synchronized void issynca(){
        try { 
            for (int i = 0; i < 5; i++) {
                thread.sleep(100); // 休眠100ms
                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); // 休眠100ms
                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); // 休眠100ms
                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); // 休眠100ms
                system.out.println(thread.currentthread().getname()+" : csyncb");
            }
        }catch (interruptedexception ie) { 
        } 
    }
}

public class locktest2 {

    something x = new something();
    something y = new something();

    // 比较(02) x.issynca()与y.issynca()
    private void test2() {
        // 新建t21, t21会调用 x.issynca()
        thread t21 = new thread(
                new runnable() {
                    @override
                    public void run() {
                        x.issynca();
                    }
                }, "t21");

        // 新建t22, t22会调用 x.issyncb()
        thread t22 = new thread(
                new runnable() {
                    @override
                    public void run() {
                        y.issynca();
                    }
                }, "t22"); 


        t21.start();  // 启动t21
        t22.start();  // 启动t22
    }

    public static void main(string[] args) {
        locktest2 demo = new locktest2();

        demo.test2();
    }
}

运行结果:

复制代码 代码如下:

t11 : issynca
t11 : issynca
t11 : issynca
t11 : issynca
t11 : issynca
t12 : issyncb
t12 : issyncb
t12 : issyncb
t12 : issyncb
t12 : issyncb

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

复制代码 代码如下:

// locktest2.java的源码
class something {
    public synchronized void issynca(){
        try { 
            for (int i = 0; i < 5; i++) {
                thread.sleep(100); // 休眠100ms
                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); // 休眠100ms
                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); // 休眠100ms
                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); // 休眠100ms
                system.out.println(thread.currentthread().getname()+" : csyncb");
            }
        }catch (interruptedexception ie) { 
        } 
    }
}

public class locktest2 {

    something x = new something();
    something y = new something();

    // 比较(02) x.issynca()与y.issynca()
    private void test2() {
        // 新建t21, t21会调用 x.issynca()
        thread t21 = new thread(
                new runnable() {
                    @override
                    public void run() {
                        x.issynca();
                    }
                }, "t21");

        // 新建t22, t22会调用 x.issyncb()
        thread t22 = new thread(
                new runnable() {
                    @override
                    public void run() {
                        y.issynca();
                    }
                }, "t22"); 


        t21.start();  // 启动t21
        t22.start();  // 启动t22
    }

    public static void main(string[] args) {
        locktest2 demo = new locktest2();

        demo.test2();
    }
}

运行结果:

复制代码 代码如下:

t21 : issynca
t22 : issynca
t21 : issynca
t22 : issynca
t21 : issynca
t22 : issynca
t21 : issynca
t22 : issynca
t21 : issynca
t22 : issynca


(03) 不能被同时访问。因为csynca()和csyncb()都是static类型,x.csynca()相当于something.issynca(),y.csyncb()相当于something.issyncb(),因此它们共用一个同步锁,不能被同时反问。

复制代码 代码如下:

// locktest3.java的源码
class something {
    public synchronized void issynca(){
        try { 
            for (int i = 0; i < 5; i++) {
                thread.sleep(100); // 休眠100ms
                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); // 休眠100ms
                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); // 休眠100ms
                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); // 休眠100ms
                system.out.println(thread.currentthread().getname()+" : csyncb");
            }
        }catch (interruptedexception ie) { 
        } 
    }
}

public class locktest3 {

    something x = new something();
    something y = new something();

    // 比较(03) x.csynca()与y.csyncb()
    private void test3() {
        // 新建t31, t31会调用 x.issynca()
        thread t31 = new thread(
                new runnable() {
                    @override
                    public void run() {
                        x.csynca();
                    }
                }, "t31");

        // 新建t32, t32会调用 x.issyncb()
        thread t32 = new thread(
                new runnable() {
                    @override
                    public void run() {
                        y.csyncb();
                    }
                }, "t32"); 


        t31.start();  // 启动t31
        t32.start();  // 启动t32
    }

    public static void main(string[] args) {
        locktest3 demo = new locktest3();

        demo.test3();
    }
}

运行结果:

复制代码 代码如下:

t31 : csynca
t31 : csynca
t31 : csynca
t31 : csynca
t31 : csynca
t32 : csyncb
t32 : csyncb
t32 : csyncb
t32 : csyncb
t32 : csyncb

(04) 可以被同时访问。因为issynca()是实例方法,x.issynca()使用的是对象x的锁;而csynca()是静态方法,something.csynca()可以理解对使用的是“类的锁”。因此,它们是可以被同时访问的。

复制代码 代码如下:

// locktest4.java的源码
class something {
    public synchronized void issynca(){
        try { 
            for (int i = 0; i < 5; i++) {
                thread.sleep(100); // 休眠100ms
                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); // 休眠100ms
                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); // 休眠100ms
                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); // 休眠100ms
                system.out.println(thread.currentthread().getname()+" : csyncb");
            }
        }catch (interruptedexception ie) { 
        } 
    }
}

public class locktest4 {

    something x = new something();
    something y = new something();

    // 比较(04) x.issynca()与something.csynca()
    private void test4() {
        // 新建t41, t41会调用 x.issynca()
        thread t41 = new thread(
                new runnable() {
                    @override
                    public void run() {
                        x.issynca();
                    }
                }, "t41");

        // 新建t42, t42会调用 x.issyncb()
        thread t42 = new thread(
                new runnable() {
                    @override
                    public void run() {
                        something.csynca();
                    }
                }, "t42"); 


        t41.start();  // 启动t41
        t42.start();  // 启动t42
    }

    public static void main(string[] args) {
        locktest4 demo = new locktest4();

        demo.test4();
    }
}


运行结果:

复制代码 代码如下:

t41 : issynca
t42 : csynca
t41 : issynca
t42 : csynca
t41 : issynca
t42 : csynca
t41 : issynca
t42 : csynca
t41 : issynca
t42 : csynca

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网