更改2.2.1代码重新测试
package com.cky.utils; /** * Created by chenkaiyang on 2017/12/6. */ public class Task { private String getData1; private String getData2; public void doLongTimeTask() { try { System.out.println("begin task"); Thread.sleep(3000); String o1 = "长时间处理任务后从远程返回的值 1 ThreadName="+ Thread.currentThread().getName(); String o2 = "长时间处理任务后从远程返回的值 2 ThreadName="+ Thread.currentThread().getName(); synchronized (this) { getData1 = o1; getData2 = o2; } System.out.println(getData1); System.out.println(getData2); System.out.println("end"); } catch (InterruptedException e) { e.printStackTrace(); } } }
D:\it\jdk1.8\bin\java -Didea.launcher.port=7538 "-Didea.launcher.bin.path=D:\it\idea\IntelliJ IDEA 2016.3.3\bin" -Dfile.encoding=UTF-8 -classpath "D:\it\jdk1.8\jre\lib\charsets.jar;D:\it\jdk1.8\jre\lib\deploy.jar;D:\it\jdk1.8\jre\lib\ext\access-bridge-64.jar;D:\it\jdk1.8\jre\lib\ext\cldrdata.jar;D:\it\jdk1.8\jre\lib\ext\dnsns.jar;D:\it\jdk1.8\jre\lib\ext\jaccess.jar;D:\it\jdk1.8\jre\lib\ext\jfxrt.jar;D:\it\jdk1.8\jre\lib\ext\localedata.jar;D:\it\jdk1.8\jre\lib\ext\nashorn.jar;D:\it\jdk1.8\jre\lib\ext\sunec.jar;D:\it\jdk1.8\jre\lib\ext\sunjce_provider.jar;D:\it\jdk1.8\jre\lib\ext\sunmscapi.jar;D:\it\jdk1.8\jre\lib\ext\sunpkcs11.jar;D:\it\jdk1.8\jre\lib\ext\zipfs.jar;D:\it\jdk1.8\jre\lib\javaws.jar;D:\it\jdk1.8\jre\lib\jce.jar;D:\it\jdk1.8\jre\lib\jfr.jar;D:\it\jdk1.8\jre\lib\jfxswt.jar;D:\it\jdk1.8\jre\lib\jsse.jar;D:\it\jdk1.8\jre\lib\management-agent.jar;D:\it\jdk1.8\jre\lib\plugin.jar;D:\it\jdk1.8\jre\lib\resources.jar;D:\it\jdk1.8\jre\lib\rt.jar;F:\springboot\threaddemo\out\production\threaddemo;D:\it\idea\IntelliJ IDEA 2016.3.3\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain com.cky.test.Test begin task begin task 长时间处理任务后从远程返回的值 1 ThreadName=Thread-0 长时间处理任务后从远程返回的值 2 ThreadName=Thread-1 end 长时间处理任务后从远程返回的值 1 ThreadName=Thread-1 长时间处理任务后从远程返回的值 2 ThreadName=Thread-1 end 耗时3
结果分析:当一个线程访问object的一个synchronized同步代码块时,另一个线程仍然可以访问该object对象非synchronized的方法。而且同步代码块里的执行是同步的。
时间: 2024-10-24 20:07:05