Java多线程4-synchronized关键字

1、synchronized原理

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

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

不同线程对同步锁的访问是互斥的,也即,在某时间点,对象的同步锁只能被一个线程获取到。通过同步锁,我们就能在多线程中,实现对“对象或方法”的互斥访问。例如现在有两个线程A和线程B,它们都会访问“对象obj”的同步锁。假设,在某一时刻,线程A获取到“obj”的同步锁并在执行一些操作;而此时线程B也希望获取“obj”的同步锁,则线程B会获取失败,它必须等待,直到线程A释放了“obj”的同步锁之后线程B才能获取到“obj”的同步锁,从而可以运行

2、synchronized基本规则

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

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

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

第一条

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

演示程序:

class MyRunnable implements Runnable
{
    @Override
    public void run()
    {
        synchronized(this)
        {
            try 
            {
                for(int i = 0;i < 5;i++)
                {
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName()+" loop "+i);
                }
            }
            catch(InterruptedException ie) {}
        }
    }
}

public class problem1 
{    
    public static void main(String[] args)
    {
        Runnable demo = new MyRunnable();
        
        Thread t1 = new Thread(demo, "t1");
        Thread t2 = new Thread(demo, "t2");
        t1.start();
        t2.start();
    }
}

运行结果:

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);
                    System.out.println(Thread.currentThread().getName()+" loop "+i);
                }
            }
            catch(InterruptedException ie) {}
        }
    }
}

public class problem1 
{    
    public static void main(String[] args)
    {
        Thread t1 = new MyThread("t1");
        Thread t2 = new MyThread("t2");
        
        t1.start();
        t2.start();
    }
}

运行结果:

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

结果说明:

synchronized(this)中的this是指“当前的类的对象”,即synchronized(this)所在的类对应的当前对象,它的作用是获取“当前对象的同步锁”。对于以上的程序,synchronized(this)中的this是指MyThread对象,而t1和t2是两个不同的MyThread对象,因此t1和t2在执行synchronized(this)时,获取的是不同对象的同步锁。而之前的代码中,synchronized(this)中的this代表的是MyRunnable对象,t1和t2共享一个MyRunnable对象,因此,一个线程获取了对象的同步锁,会造成另外一个线程等待

第二条

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

演示程序:

class Count
{
    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 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 problem1 
{    
    public static void main(String[] args)
    {
        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();
    }
}

运行结果:

t2 nonSynMethod loop 0
t1 synMethod loop 0
t2 nonSynMethod loop 1
t1 synMethod 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代码块”的访问将被阻塞

演示程序:

class Count
{
    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 ie) {}
        }
    }
    
    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 problem1 
{    
    public static void main(String[] args)
    {
        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 synMethod loop 0
t1 synMethod loop 1
t1 synMethod loop 2
t1 synMethod loop 3
t1 synMethod loop 4
t2 nonSynMethod loop 0
t2 nonSynMethod loop 1
t2 nonSynMethod loop 2
t2 nonSynMethod loop 3
t2 nonSynMethod loop 4

结果说明:

主线程中创建了两个子线程t1和t2。它们运行时都调用synchronized(this),这个this是count对象,而t1和t2共用count。因此,在t1运行的时候,t2会被阻塞,等待t1运行释放count对象的同步锁,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("Synchronnized method");
    }
}

synchronized代码块可以更精确地控制冲突限制访问区域,有时候表现更高效率。下面是演示程序:

public class Problem1 
{    
    public synchronized void synMethod()
    {
        for(int i = 0;i < 1000000;i++)
            ;
    }
    
    public void synBlock()
    {
        synchronized(this)
        {
            for(int i = 0;i <1000;i++)
                ;
        }
    }
    public static void main(String[] args)
    {
        Problem1 demo = new Problem1();
        long start;
        long 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(): 2
synBlock(): 0

4、实例锁 和 全局锁

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

全局锁--该锁针对的是类,无论实例多少个对象,那么线程都共享该锁。全局锁对应的是static synchronized(或者是锁在该类的class或者class loader对象上)

一个例子:

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

己设,something类有两个实例x和y。分析以下四组表达式获取的锁的情况:

(1)、x.isSyncA()与x.isSyncB()

(2)、x.isSyncA()与y.isSyncA()

(3)、x.cSyncA()与y.cSyncB()

(4)、x.isSyncA()与Something.cSyncA()

(1)、不能同时访问,因为访问的是同一个对象x的同步锁

class Something
{
    public synchronized void isSyncA()
    {
        synchronized(this)
        {
            try
            {
                for(int i = 0;i < 5;i++)
                {
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName()+" synMethod loop "+i);
                }
            }
            catch(InterruptedException ie) {}
        }
    }
    
    public synchronized void isSyncB()
    {
        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 Problem1 
{    
    Something x = new Something();
    Something y = new Something();
    
    private void test1()
    {
        Thread t1 = new Thread(
                new Runnable(){
                    @Override
                    public void run()
                    {
                        x.isSyncA();
                    }
                },"t1");
        
        Thread t2 = new Thread(
                new Runnable() {
                    @Override
                    public void run()
                    {
                        x.isSyncB();
                    }
                },"t2");
        
        t1.start();
        t2.start();
    }
    public static void main(String[] args)
    {
        Problem1 demo = new Problem1();
        demo.test1();
    }
}

运行结果:

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

(2)、可以同时被访问,x.isSyncA()访问的是x的同步锁,而y.isSyncA()访问的是y的同步锁

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

public class Problem1 
{    
    Something x = new Something();
    Something y = new Something();
    
    private void test1()
    {
        Thread t1 = new Thread(
                new Runnable(){
                    @Override
                    public void run()
                    {
                        x.isSyncA();
                    }
                },"t1");
        
        Thread t2 = new Thread(
                new Runnable() {
                    @Override
                    public void run()
                    {
                        y.isSyncB();
                    }
                },"t2");
        
        t1.start();
        t2.start();
    }
    public static void main(String[] args)
    {
        Problem1 demo = new Problem1();
        demo.test1();
    }
}

运行结果:

t1 isSyncA 0
t2 isSyncB 0
t1 isSyncA 1
t2 isSyncB 1
t1 isSyncA 2
t2 isSyncB 2
t1 isSyncA 3
t2 isSyncB 3
t1 isSyncA 4
t2 isSyncB 4

(3)、不能被同时访问,因为cSyncA()和cSyncB()都是static类型,x.cSynca()相当于Something.isSyncA(),y.cSyncB()相当于Something.isSyncB(),因此它们共用同一把锁

class Something
{
    public synchronized void isSyncA()
    {
        synchronized(this)
        {
            try
            {
                for(int i = 0;i < 5;i++)
                {
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName()+" isSyncA "+i);
                }
            }
            catch(InterruptedException ie) {}
        }
    }
    
    public synchronized void isSyncB()
    {
        synchronized(this)
        {
            try
            {
                for(int i = 0;i < 5;i++)
                {
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName()+" isSyncB "+i);
                }
            }
            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 "+i);
            }
        }
        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 "+i);
            }
        }
        catch(InterruptedException ie) {}
    }
}

public class Problem1 
{    
    Something x = new Something();
    Something y = new Something();
    
    private void test1()
    {
        Thread t1 = new Thread(
                new Runnable(){
                    @Override
                    public void run()
                    {
                        x.cSyncA();
                    }
                },"t1");
        
        Thread t2 = new Thread(
                new Runnable() {
                    @Override
                    public void run()
                    {
                        y.cSyncB();
                    }
                },"t2");
        
        t1.start();
        t2.start();
    }
    public static void main(String[] args)
    {
        Problem1 demo = new Problem1();
        demo.test1();
    }
}

运行结果:

t1 cSyncA 0
t1 cSyncA 1
t1 cSyncA 2
t1 cSyncA 3
t1 cSyncA 4
t2 cSyncB 0
t2 cSyncB 1
t2 cSyncB 2
t2 cSyncB 3
t2 cSyncB 4

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

class Something
{
    public synchronized void isSyncA()
    {
        synchronized(this)
        {
            try
            {
                for(int i = 0;i < 5;i++)
                {
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName()+" isSyncA "+i);
                }
            }
            catch(InterruptedException ie) {}
        }
    }
    
    public synchronized void isSyncB()
    {
        synchronized(this)
        {
            try
            {
                for(int i = 0;i < 5;i++)
                {
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName()+" isSyncB "+i);
                }
            }
            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 "+i);
            }
        }
        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 "+i);
            }
        }
        catch(InterruptedException ie) {}
    }
}

public class Problem1 
{    
    Something x = new Something();
    Something y = new Something();
    
    private void test1()
    {
        Thread t1 = new Thread(
                new Runnable(){
                    @Override
                    public void run()
                    {
                        x.isSyncA();
                    }
                },"t1");
        
        Thread t2 = new Thread(
                new Runnable() {
                    @Override
                    public void run()
                    {
                        Something.cSyncA();
                    }
                },"t2");
        
        t1.start();
        t2.start();
    }
    public static void main(String[] args)
    {
        Problem1 demo = new Problem1();
        demo.test1();
    }
}

运行结果:

t2 cSyncA 0
t1 isSyncA 0
t2 cSyncA 1
t1 isSyncA 1
t2 cSyncA 2
t1 isSyncA 2
t1 isSyncA 3
t2 cSyncA 3
t2 cSyncA 4
t1 isSyncA 4
原文地址:https://www.cnblogs.com/qumasha/p/12824905.html