標籤:
package testSynchronized;/** * * 當使用this也就是該檔案中的testclass對象作為對象鎖時, * 兩個線程都使用該對象鎖訪問該對象的同步代碼塊, * 是順序執行的, * 也就是說當一個線程使用testclass對象對這段同步代碼塊上鎖了以後, * 另一個線程無法再使用testclass對象進入該同步代碼塊 * 理解: * 因為該鎖標記對象已經被標記為正在使用,所以只能排隊 * */class TestClass { public void f(){ synchronized(this){ for(int i = 0 ; i < 1000 ; i ++){ System.out.println("i: " + i ); } } }}class ThreadTest extends Thread { private TestClass testclass ; public ThreadTest(TestClass testclass) { this.testclass = testclass ; } @Override public void run() { testclass.f(); }}public class TestSynchroinzed { public static void main(String[] args) { TestClass testclass = new TestClass() ; ThreadTest thread1 = new ThreadTest(testclass) ; ThreadTest thread2 = new ThreadTest(testclass) ; thread1.start(); thread2.start(); }}
在來一個:
package testSynchronized;/** * * 在該類中測試兩個線程使用不同的鎖對象,觀察能不能同時訪問一個同步代碼塊 * * 出現的結果和TestSynchronized相反。這兩個線程可以同時進入該同步代碼塊執行。 * * why ??????? * * 測試結果表明: * 使用同一對象鎖的多個線程需要排隊訪問 * 使用不同對象鎖的多個線程可以同時訪問(完全是不同的對象,不同的記憶體空間,當然不存線上程問題) * * 似乎明白了: * 使用this作為鎖標記,當一個線程使用這個鎖標記鎖住某些 * (可以使用一個線程同時訪問使用一個對象標記鎖的多個同步代碼塊, * 那麼這個線程就使用該對象鎖住了多個同步代碼塊)代碼塊後, * 其他的線程準備執行這個對象的這個同步代碼塊時, * 會被告知這個this對象正在被使用鎖住一些同步代碼,還沒有被釋放,所以無法使用該鎖進入同步代碼塊。 * 只有使用該鎖鎖住的所有同步代碼塊都執行結束的後, * 其他的線程才能夠重新使用該對象作為鎖標記進入同步代碼塊 * * 但是如果調用的就是不同的對象方法, * 那麼就不會存在同步的問題, * 因為完全是兩個不同的方法,不同的記憶體空間。 */class TestClass1 { public void f(){ synchronized(this){ while(true); } } public void f2(){ synchronized(this){ for(int i = 0 ; i < 100 ; i ++){ System.out.println("################"); } } }}class ThreadTest1 extends Thread { private TestClass1 testclass ; public ThreadTest1(TestClass1 testclass) { this.testclass = testclass ; } @Override public void run() { testclass.f(); }}class ThreadTest2 extends Thread { private TestClass1 testclass ; public ThreadTest2(TestClass1 testclass) { this.testclass = testclass ; } @Override public void run() { testclass.f2(); }}public class TestSynchronized2 { public static void main(String[] args) { TestClass1 testclass = new TestClass1() ; TestClass1 testclass2 = new TestClass1() ; ThreadTest1 thread1 = new ThreadTest1(testclass) ; ThreadTest2 thread2 = new ThreadTest2(testclass) ; thread1.start(); thread2.start(); }}
關於java多線程