蘋果的成長日記

          我還是個青蘋果呀!

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            57 隨筆 :: 0 文章 :: 74 評論 :: 0 Trackbacks
          接觸多線程已經不少時間了,也做了不少事情,但是一直覺得用起來不那么順手,在debug的時候,往往會比較擔心在同步上出什么問題,想起"程序員最怕的是自己寫的代碼"這句話,覺得真是不假.
              終于有一天,我覺得是時候把這個問題弄清楚了,所以,我就在網上找相關的內容看,結果竟然是找不到在我這個階段應該看的,不是太簡單,就是一筆帶過,不知所云.
              廢了九牛二虎之力,終于差不多弄清楚了,其中有不少誤區,以前認為的和真理相差甚大.想起自己花費的時間,真是覺得有點多,所以把它寫出來,一是防止自己以后又會忘掉,二是給像我一樣的似懂非懂者留下一點可以參考的東東.
              閑話少說,轉入正題!
            ---------------------------------
              先從線程的創建說起.線程的創建一共有兩種形式:
            ---------------------------------

              一種是繼承自Thread類.Thread 類是一個具體的類,即不是抽象類,該類封裝了線程的行為。要創建一個線程,程序員必須創建一個從 Thread 類導出的新類。程序員通過覆蓋 Thread 的 run() 函數來完成有用的工作。用戶并不直接調用此函數;而是通過調用 Thread 的 start() 函數,該函數再調用 run()。
             
              例如:

              public class Test extends Thread{
                public Test(){
                }
                public static void main(String args[]){
                  Test t1 = new Test();
                  Test t2 = new Test();
                  t1.start();
                  t2.start();
                }
                public void run(){
                  //do thread's things
                }
              }

          ----------------------------
             
              另一種是實現Runnable接口,此接口只有一個函數,run(),此函數必須由實現了此接口的類實現。
             
              例如: public class Test implements Runnable{
                Thread thread1;
                Thread thread2;
                public Test(){
                  thread1 = new Thread(this,"1");
                  thread2 = new Thread(this,"2");
                }
                public static void main(String args[]){
                  Test t = new Test();
                  t.startThreads();
                }
                public void run(){
                  //do thread's things
                }
                public void startThreads(){
                  thread1.start();
                  thread2.start();
                }
              }

              兩種創建方式差別不大,第一種因為繼承自Thread,只創建了自身對象,第二種還得創建Thread對象.但是當你想繼承某一其它類時,你只能用后一種方式.大多數人偏愛后一種的原因大概也在于此吧.

          -------------------------

              下面我們來講synchronized的4種用法吧:

              1.方法聲明時使用,放在范圍操作符(public等)之后,返回類型聲明(void等)之前.這時,線程獲得的是成員鎖,即一次只能有一個線程進入該方法,其他線程要想在此時調用該方法,只能排隊等候,當前線程(就是在synchronized方法內部的線程)執行完該方法后,別的線程才能進入.
           
                例如:

                public synchronized void synMethod() {
                  //方法體
                }

              2.對某一代碼塊使用,synchronized后跟括號,括號里是變量,這樣,一次只有一個線程進入該代碼塊.此時,線程獲得的是成員鎖.例如:

          public int synMethod(int a1){
                  synchronized(a1) {
                    //一次只能有一個線程進入
                  }
                }
              3.synchronized后面括號里是一對象,此時,線程獲得的是對象鎖.例如:

            public class MyThread implements Runnable {
              public static void main(String args[]) {
              MyThread mt = new MyThread();
              Thread t1 = new Thread(mt, "t1");
              Thread t2 = new Thread(mt, "t2");
              Thread t3 = new Thread(mt, "t3");
              Thread t4 = new Thread(mt, "t4");
              Thread t5 = new Thread(mt, "t5");
              Thread t6 = new Thread(mt, "t6");
              t1.start();
              t2.start();
              t3.start();
              t4.start();
              t5.start();
              t6.start();
            }

            public void run() {
              synchronized (this) {
                System.out.println(Thread.currentThread().getName());
              }
            }
          }
           
              對于3,如果線程進入,則得到當前對象鎖,那么別的線程在該類所有對象上的任何操作都不能進行.在對象級使用鎖通常是一種比較粗糙的方法。為什么要將整個對象都上鎖,而不允許其他線程短暫地使用對象中其他同步方法來訪問共享資源?如果一個對象擁有多個資源,就不需要只為了讓一個線程使用其中一部分資源,就將所有線程都鎖在外面。由于每個對象都有鎖,可以如下所示使用虛擬對象來上鎖:class FineGrainLock {

             MyMemberClass x, y;
             Object xlock = new Object(), ylock = new Object();

             public void foo() {
                synchronized(xlock) {
                   //access x here
                }

                //do something here - but don't use shared resources

                synchronized(ylock) {
                   //access y here
                }
             }

             public void bar() {
                synchronized(this) {
                   //access both x and y here
                }
                //do something here - but don't use shared resources
             }
            }

              4.synchronized后面括號里是類,此時,線程獲得的是對象鎖.例如:

            class ArrayWithLockOrder{
            private static long num_locks = 0;
            private long lock_order;
            private int[] arr;

            public ArrayWithLockOrder(int[] a)
            {
              arr = a;
              synchronized(ArrayWithLockOrder.class) {//-----這里
                num_locks++;             // 鎖數加 1。
                lock_order = num_locks;  // 為此對象實例設置唯一的 lock_order。
              }
            }
            public long lockOrder()
            {
              return lock_order;
            }
            public int[] array()
            {
              return arr;
            }
            }

            class SomeClass implements Runnable
           {
            public int sumArrays(ArrayWithLockOrder a1,
                                 ArrayWithLockOrder a2)
            {
              int value = 0;
              ArrayWithLockOrder first = a1;       // 保留數組引用的一個
              ArrayWithLockOrder last = a2;        // 本地副本。
              int size = a1.array().length;
              if (size == a2.array().length)
              {
                if (a1.lockOrder() > a2.lockOrder())  // 確定并設置對象的鎖定
                {                                     // 順序。
                  first = a2;
                  last = a1;
                }
                synchronized(first) {              // 按正確的順序鎖定對象。
                  synchronized(last) {
                    int[] arr1 = a1.array();
                    int[] arr2 = a2.array();
                    for (int i=0; i<size; i++)
                      value += arr1[i] + arr2[i];
                  }
                }
              }
              return value;
          }
            public void run() {
              //...
            }
            }
              對于4,如果線程進入,則線程在該類中所有操作不能進行,包括靜態變量和靜態方法,實際上,對于含有靜態方法和靜態變量的代碼塊的同步,我們通常用4來加鎖.

            -----------------------------

            下面談一談一些常用的方法:

            wait(),wait(long),notify(),notifyAll()等方法是當前類的實例方法,
             
                  wait()是使持有對象鎖的線程釋放鎖;
                  wait(long)是使持有對象鎖的線程釋放鎖時間為long(毫秒)后,再次獲得鎖,wait()和wait(0)等價;
                  notify()是喚醒一個正在等待該對象鎖的線程,如果等待的線程不止一個,那么被喚醒的線程由jvm確定;
                  notifyAll是喚醒所有正在等待該對象鎖的線程.
                  在這里我也重申一下,我們應該優先使用notifyAll()方法,因為喚醒所有線程比喚醒一個線程更容易讓jvm找到最適合被喚醒的線程.

              對于上述方法,只有在當前線程中才能使用,否則報運行時錯誤java.lang.IllegalMonitorStateException: current thread not owner.

            --------------------------

              下面,我談一下synchronized和wait()、notify()等的關系:

              其實用生產者/消費者這個例子最好說明他們之間的關系了:

              public class test {
            public static void main(String args[]) {
              Semaphore s = new Semaphore(1);
              Thread t1 = new Thread(s, "producer1");
              Thread t2 = new Thread(s, "producer2");
              Thread t3 = new Thread(s, "producer3");
              Thread t4 = new Thread(s, "consumer1");
              Thread t5 = new Thread(s, "consumer2");
           Thread t6 = new Thread(s, "consumer3");
              t1.start();
              t2.start();
              t3.start();
              t4.start();
              t5.start();
              t6.start();
            }
            }

            class Semaphore
               implements Runnable {
            private int count;
            public Semaphore(int n) {
              this.count = n;
            }

            public synchronized void acquire() {
              while (count == 0) {
                try {
                  wait();
                }
                catch (InterruptedException e) {
                  //keep trying
                }
              }
              count--;
            }

            public synchronized void release() {
              while (count == 10) {
                try {
                  wait();
                }
            catch (InterruptedException e) {
                  //keep trying
                }
              }
              count++;
              notifyAll(); //alert a thread that's blocking on this semaphore
            }

            public void run() {
              while (true) {
                if (Thread.currentThread().getName().substring(0,8).equalsIgnoreCase("consumer")) {
                  acquire();
                }
                else if (Thread.currentThread().getName().substring(0,8).equalsIgnoreCase("producer")) {
                  release();
                }
                System.out.println(Thread.currentThread().getName() + " " + count);
              }
              }
            }
                 生產者生產,消費者消費,一般沒有沖突,但當庫存為0時,消費者要消費是不行的,但當庫存為上限(這里是10)時,生產者也不能生產.請好好研讀上面的程序,你一定會比以前進步很多.

                上面的代碼說明了synchronized和wait,notify沒有絕對的關系,在synchronized聲明的方法、代碼塊中,你完全可以不用wait,notify等方法,但是,如果當線程對某一資源存在某種爭用的情況下,你必須適時得將線程放入等待或者喚醒.

          文章終于寫完了,基本上將我學習所得全部寫出來了,不過也留下些許遺憾,比如synchronized后是類時的深入的說明及討論.而且,文章由于自己能力有限,有些地方肯定會有錯誤,希望看過有何建議和批評,請發帖在下面,我會修正該文.謝謝!

          posted on 2005-06-24 13:48 蘋果 閱讀(367) 評論(0)  編輯  收藏 所屬分類: J2EE/JAVA學習
          主站蜘蛛池模板: 五莲县| 衡东县| 浦县| 大同市| 沈丘县| 河津市| 英山县| 那曲县| 张北县| 沂南县| 漳浦县| 无为县| 东乌珠穆沁旗| 河曲县| 盐山县| 同仁县| 萨嘎县| 鄄城县| 衢州市| 沁源县| 库车县| 兖州市| 二连浩特市| 新宾| 无棣县| 馆陶县| 得荣县| 木兰县| 龙州县| 满城县| 分宜县| 上林县| 广西| 永康市| 东兰县| 湄潭县| 化隆| 高邑县| 兴国县| 上栗县| 萝北县|