synchronized线程同步锁

来源:互联网 发布:移动是什么网络模式 编辑:程序博客网 时间:2024/05/18 21:06

在Java中,synchronized关键字是用来控制线程同步的。synchronized既可以加在一段代码上,也可以加在方法上。

下面主要来讲讲对象锁的概念,通过例子帮助读者理解:

class Test{    public synchronized void test() {        System.out.println("test begin");        try {            Thread.sleep(1000);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println("test end");    }}class MyThread extends Thread {    public void run() {        Test test= new Test();        test.test();    }}public class Main {    public static void main(String[] args) {        for (int i = 0; i < 3; i++) {            Thread thread = new MyThread();            thread.start();        }    }}

运行结果:

test begin test begin test begin  test end test end test end

似乎synchronized没有起到作用,多线程访问的时候还是没有同步,为什么呢?

实际上,synchronized(this)以及非static的synchronized方法,只能防止多个线程同时执行同一个对象的同步代码段,也就是说上例并非是同一个对象,而是多个对象。需要强调的是,synchronized锁住的是括号里的对象,而不是代码。对于非static的synchronized方法,锁的就是对象本身也就是this。

当synchronized锁住一个对象后,别的线程如果也想拿到这个对象的锁,就必须等待这个线程执行完成释放锁,才能再次给对象加锁,这样才达到线程同步的目的。即使两个不同的代码段,都要锁同一个对象,那么这两个代码段也不能在多线程环境下同时运行。

所以我们在用synchronized关键字的时候,能缩小代码段的范围就尽量缩小,能在代码段上加同步就不要再整个方法上加同步。这叫减小锁的粒度,使代码更大程度的并发。

再看上面的代码,每个线程中都new了一个Test类的对象,也就是产生了三个Test对象,由于不是同一个对象,所以可以多线程同时运行synchronized方法或代码段。

为了验证上述的观点,修改一下代码,让三个线程使用同一个Test的对象。

class MyThread extends Thread {    private Test  test;    public MyThread(Test  test) {        this.test= test;    }    public void run() {        test.test();    }}public class Main {    public static void main(String[] args) {        Test test= new Test();        for (int i = 0; i < 3; i++) {            Thread thread = new MyThread(test);            thread.start();        }    }}

运行结果:

test begin test end test begin  test end test begin  test end

可以看到,此时的synchronized就起了作用。

那么,如果真的想锁住这段代码,要怎么做?也就是,如果还是最开始的那段代码,每个线程new一个Test对象,怎么才能让test方法不会被多线程执行。

解决也很简单,只要锁住同一个Class对象不就行了。比较多的做法是让synchronized锁这个类对应的Class对象。

class Test{    public void test() {        synchronized (Test.class) {            System.out.println("test begin");            try {                Thread.sleep(1000);            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println("test end");        }    }}class MyThread extends Thread {    public void run() {        Test test= new Test();        test.test();    }}public class Main {    public static void main(String[] args) {        for (int i = 0; i < 3; i++) {            Thread thread = new MyThread();            thread.start();        }    }}

运行结果:

test begin test end test begin  test end test begin  test end

上面代码用synchronized(Test.class)实现了全局锁的效果。

static synchronized方法,static方法可以直接类名加方法名调用,方法中无法使用this,所以它锁的不是this,而是类的Class对象,所以,static synchronized方法也相当于全局锁,相当于锁住了代码段。

0 0
原创粉丝点击