package 对象及变量的并发访问2;
/**
* 用同步代码块解决同步方法的弊端
*
* 从结果看: 当一个线程访问object的一个synchronized同步代码块时,另一个线程仍然可以访问该object对象中的非synchronized(this)同步代码块
*
*/
class TaskT2230{
private String getDate1;
private String getDate2;
public void doLongTimeTask(){
try {
System.out.println("begin task");
Thread.sleep(3000);
String privateGetDate1="长时间处理任务从远程返回的值1 threadName="+Thread.currentThread().getName();
String privateGetDate2="长时间处理任务从远程返回的值2 threadName="+Thread.currentThread().getName();
synchronized (this){
getDate1=privateGetDate1;
getDate2=privateGetDate2;
System.out.println(getDate1);
System.out.println(getDate2);
System.out.println("end task");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class CommonutilsT2230{
public static long beginTime1;
public static long endTime1;
public static long beginTime2;
public static long endTime2;
}
class MyThreadT2230 extends Thread{
private TaskT2230 taskT2230;
public MyThreadT2230(TaskT2230 taskT2230){
super();
this.taskT2230=taskT2230;
}
@Override
public void run() {
super.run();
CommonutilsT2230.beginTime1=System.currentTimeMillis();
taskT2230.doLongTimeTask();
CommonutilsT2210.endTime1=System.currentTimeMillis();
}
}
class MyThread2T2230 extends Thread{
private TaskT2230 taskT2230;
public MyThread2T2230(TaskT2230 taskT2230){
super();
this.taskT2230=taskT2230;
}
@Override
public void run() {
super.run();
CommonutilsT2230.beginTime2=System.currentTimeMillis();
taskT2230.doLongTimeTask();
CommonutilsT2230.endTime2=System.currentTimeMillis();
}
}
class RunT2230{
public RunT2230(){
TaskT2230 taskT2230=new TaskT2230();
MyThreadT2230 myThreadT2230=new MyThreadT2230(taskT2230);
myThreadT2230.start();
MyThread2T2230 myThread2T2230=new MyThread2T2230(taskT2230);
myThread2T2230.start();
try {
//为了造成时差
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long beginTime=CommonutilsT2230.beginTime1;
if(CommonutilsT2230.beginTime2<CommonutilsT2230.beginTime1){
beginTime=CommonutilsT2230.beginTime2;
}
long endTime=CommonutilsT2230.endTime1;
if(CommonutilsT2230.endTime2>CommonutilsT2230.endTime1){
endTime=CommonutilsT2230.endTime2;
}
System.out.println("耗时:"+((endTime-beginTime)/1000));
}
}
public class T2203 {
public static void main(String[] args) {
RunT2230 runT2230=new RunT2230();
}
}
用同步代码块解决同步方法的弊端——T2203
最新推荐文章于 2022-06-08 10:51:23 发布