Java多线程编程核心技术(第3版)
上QQ阅读APP看书,第一时间看更新

2.2.5 synchronized代码块间的同步性

在使用synchronized(this)同步代码块时需要注意的是,当一个线程访问object的一个synchronized(this)同步代码块时,其他线程对同一个object中所有其他synchronized(this)同步代码块的访问将被阻塞,说明synchronized使用的“对象监视器”是一个,即使用的“锁”是一个。

创建验证项目doubleSynBlockOneTwo,类文件ObjectService.java代码如下:


package service;

public class ObjectService {

public void serviceMethodA() {
    try {
        synchronized (this) {
            System.out.println("A begin time=" + System.currentTimeMillis());
            Thread.sleep(2000);
            System.out.println("A end    end=" + System.currentTimeMillis());
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public void serviceMethodB() {
    synchronized (this) {
        System.out.println("B begin time=" + System.currentTimeMillis());
        System.out.println("B end    end=" + System.currentTimeMillis());
    }
}
}

自定义线程类ThreadA.java代码如下:


package extthread;

import service.ObjectService;

public class ThreadA extends Thread {

private ObjectService service;

public ThreadA(ObjectService service) {
    super();
    this.service = service;
}

@Override
public void run() {
    super.run();
    service.serviceMethodA();
}

}

自定义线程类ThreadB.java代码如下:


package extthread;

import service.ObjectService;

public class ThreadB extends Thread {
private ObjectService service;

public ThreadB(ObjectService service) {
    super();
    this.service = service;
}

@Override
public void run() {
    super.run();
    service.serviceMethodB();
}
}

运行类Run.java代码如下:


package test.run;

import service.ObjectService;
import extthread.ThreadA;
import extthread.ThreadB;

public class Run {

public static void main(String[] args) {
    ObjectService service = new ObjectService();

    ThreadA a = new ThreadA(service);
    a.setName("a");
    a.start();

    ThreadB b = new ThreadB(service);
    b.setName("b");
    b.start();
}

}

程序运行结果如图2-26所示。

图2-26 两个同步代码块按顺序执行