public class Test176 {
synchronized public void show() {
String s1 = "這是處理的任務1"+Thread.currentThread().getName();
String s2 = "這是處理的任務2"+Thread.currentThread().getName();
try {
Thread.sleep();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(s1);
System.out.println(s2);
}
}
package com.example.test;
public class Test177 {
public static void main(String[] args) {
Test176 t = new Test176();
MyThreadSix mts = new MyThreadSix(t);
Thread t1 = new Thread(mts);
Thread t2 = new Thread(mts);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
class MyThreadSix implements Runnable{
private Test176 t;
public MyThreadSix(Test176 t) {
super();
this.t = t;
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName()+"開始時間"+System.currentTimeMillis());
t.show();
System.out.println(Thread.currentThread().getName()+"結束時間"+System.currentTimeMillis());
}
}
在上述的代碼中,用時間毫秒數大的結束時間-時間毫秒數小的開始時間得出兩個線程全部完成的總時間。
将代碼修改如下:
public void show() {
String s1 = "這是處理的任務1"+Thread.currentThread().getName();
String s2 = "這是處理的任務2"+Thread.currentThread().getName();
try {
Thread.sleep();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (this) {
System.out.println(s1);
System.out.println(s2);
}
}
你在運作,會發現,執行時間短了。這也引出了synchronized 代碼塊執行效率比synchronized 修飾方法要高。
但是我們要搞清楚,為啥呢,synchronized 修飾方法,那麼另外線程就必須等待整個方法執行完畢,你要知道一些方法可能有一些耗時操作,這些耗時操作可以異步做,主要是在擷取資料,或者關鍵的修改地方是必須同步,是以你何苦要封鎖整個方法。通過本文的例子,希望能了解這點。