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

2.2.15 同步synchronized方法可以对类的所有对象实例起作用

Class锁可以对同一个类的所有对象实例起作用,实现同步效果。

用项目synMoreObjectStaticOneLock来验证,类文件Service.java代码如下:


package service;

public class Service {

synchronized public static void printA() {
    try {
        System.out.println("线程名称为:" + Thread.currentThread().getName()
            + "在" + System.currentTimeMillis() + "进入printA");
        Thread.sleep(3000);
        System.out.println("线程名称为:" + Thread.currentThread().getName()
            + "在" + System.currentTimeMillis() + "离开printA");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

synchronized public static void printB() {
    System.out.println("线程名称为:" + Thread.currentThread().getName() + "在"
        + System.currentTimeMillis() + "进入printB");
    System.out.println("线程名称为:" + Thread.currentThread().getName() + "在"
        + System.currentTimeMillis() + "离开printB");
}

}

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


package extthread;

import service.Service;

public class ThreadA extends Thread {
private Service service;

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

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

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


package extthread;

import service.Service;

public class ThreadB extends Thread {
private Service service;

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

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

运行类Run.java代码如下:


package test;

import service.Service;
import extthread.ThreadA;
import extthread.ThreadB;

public class Run {

public static void main(String[] args) {

    Service service1 = new Service();
    Service service2 = new Service();

    ThreadA a = new ThreadA(service1);
    a.setName("A");
    a.start();

    ThreadB b = new ThreadB(service2);
    b.setName("B");
    b.start();

}

}

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

图2-45 虽然是不同对象,但静态的同步方法还是同步运行