接上篇,是由一個對象來訪問多個線程,這時只須要將方法加上synchronized便可實現,可是若是由多個對象來調多個線程,會是什麼狀況,以下線程
public class SychronizeTest { public static void main(String[] args) { Task t = new Task(); ThreadA ta = new ThreadA(t); t = new Task(); //生成第二個對象 ThreadB tb = new ThreadB(t); ta.start(); tb.start(); } }
你能夠嘗試執行一個結果,確定是亂序的。 這種狀況就須要加一個類級別的鎖code
class Task { public synchronized static void excute1(String threadName) { for (int i = 0; i <= 20; i++) { System.out.println(threadName + " ------ " + i); } } public synchronized static void excute2(String threadName){ for (int i = 0; i <= 20; i++) { System.out.println(threadName + " ------ " + i); } } }
當synchronized 與static共用時,這個時候,鎖的級別不在對象上,而在對象所對應的類上,即便你從新生成 N個對象,在JAVA中,這些對象會對應惟一一個class對象,因此經過上面的方法,能夠按照順序,執行完一個,再執行另外一個。對象