/**
* 線程任務(wù)
* 用同步代碼塊解決同步方法的弊端
* @author wuyoushan
* @date 2017/1/23.
*/
public class Task {
private String getData1;
private String getData2;
public void doLongTimeTask(){
try {
System.out.println("begin task");
Thread.sleep(3000);
String privateGetData1="長(zhǎng)時(shí)間處理任務(wù)后從遠(yuǎn)程返回的值1 threadName="+
Thread.currentThread().getName();
String privateGetData2="長(zhǎng)時(shí)間處理任務(wù)后從遠(yuǎn)程返回的值2 threadName="+
Thread.currentThread().getName();
synchronized (this){
getData1=privateGetData1;
getData2=privateGetData2;
}
System.out.println(getData1);
System.out.println(getData2);
System.out.println("end task");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 常量定義
* 用同步代碼塊解決同步方法的弊端
* @author wuyoushan
* @date 2017/1/23.
*/
public class CommonUtils {
public static long beginTime1;
public static long endTime1;
public static long beginTime2;
public static long endTime2;
}
/**線程1
* 用同步代碼塊解決同步方法的弊端
* @author wuyoushan
* @date 2017/1/23.
*/
public class MyThread1 extends Thread {
private Task task;
public MyThread1(Task task){
this.task=task;
}
@Override
public void run() {
super.run();
CommonUtils.beginTime1=System.currentTimeMillis();
task.doLongTimeTask();
CommonUtils.endTime1=System.currentTimeMillis();
}
}
/**
* 線程二
* synchronized方法的弊端
* @author wuyoushan
* @date 2017/1/23.
*/
public class MyThread2 extends Thread {
private Task task;
public MyThread2(Task task){
this.task=task;
}
@Override
public void run() {
super.run();
CommonUtils.beginTime2=System.currentTimeMillis();
task.doLongTimeTask();
CommonUtils.endTime2=System.currentTimeMillis();
}
}
/**運(yùn)行實(shí)例
* 用同步代碼塊解決同步方法的弊端
* @author wuyoushan
* @date 2017/1/23.
*/
public class Run {
public static void main(String[] args) {
Task task=new Task();
MyThread1 thread1=new MyThread1(task);
thread1.start();
MyThread2 thread2=new MyThread2(task);
thread2.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long beginTime=CommonUtils.beginTime1;
if (CommonUtils.beginTime2<CommonUtils.beginTime1){
beginTime=CommonUtils.beginTime2;
}
long endTime=CommonUtils.endTime1;
if (CommonUtils.endTime2>CommonUtils.endTime1){
endTime=CommonUtils.endTime2;
}
System.out.println("耗時(shí):"+((endTime-beginTime)/1000));
}
}
程序的運(yùn)行結(jié)果為:
begin task
begin task
長(zhǎng)時(shí)間處理任務(wù)后從遠(yuǎn)程返回的值1 threadName=Thread-1
長(zhǎng)時(shí)間處理任務(wù)后從遠(yuǎn)程返回的值2 threadName=Thread-0
end task
長(zhǎng)時(shí)間處理任務(wù)后從遠(yuǎn)程返回的值1 threadName=Thread-0
長(zhǎng)時(shí)間處理任務(wù)后從遠(yuǎn)程返回的值2 threadName=Thread-0
end task
耗時(shí):3
通過上面的實(shí)驗(yàn)可以得知协饲,當(dāng)一個(gè)線程訪問object的一個(gè)synchronized同步代碼塊時(shí)锣披,另一個(gè)線程仍然可以訪問改object對(duì)象中的非synchronized(this)同步代碼塊缘眶。
實(shí)驗(yàn)進(jìn)行到這里,雖然時(shí)間縮短谓谦,運(yùn)行效率加快酝碳,但同步synchronized代碼塊真的是同步的嗎?真的持有當(dāng)前調(diào)用對(duì)象的鎖嗎户辱?答案為是鸵钝,但必須用代碼的方式來進(jìn)行驗(yàn)證
摘選自 java多線程核心編程技術(shù)-2.2.3