
上QQ阅读APP看书,第一时间看更新
2.2.16 同步synchronized(class)代码块可以对类的所有对象实例起作用
同步synchronized(class)代码块的作用其实和synchronized静态方法的作用一样。创建测试项目synBlockMoreObjectOneLock,类文件Service.java代码如下:
package service; public class Service { public void printA() { synchronized (Service.class) { 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(); } } } public void printB() { synchronized (Service.class) { System.out.println("线程名称为:" + Thread.currentThread().getName() + "在" + System.currentTimeMillis() + "进入printB"); System.out.println("线程名称为:" + Thread.currentThread().getName() + "在" + System.currentTimeMillis() + "离开printB"); } } }
两个自定义线程代码如图2-46所示。

图2-46 两个自定义线程代码
运行类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-47所示。

图2-47 同步运行