<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    蘋果的成長日記

    我還是個青蘋果呀!

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

        一種是繼承自Thread類.Thread 類是一個具體的類,即不是抽象類,該類封裝了線程的行為。要創(chuàng)建一個線程,程序員必須創(chuàng)建一個從 Thread 類導(dǎo)出的新類。程序員通過覆蓋 Thread 的 run() 函數(shù)來完成有用的工作。用戶并不直接調(diào)用此函數(shù);而是通過調(diào)用 Thread 的 start() 函數(shù),該函數(shù)再調(diào)用 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
          }
        }

    ----------------------------
       
        另一種是實(shí)現(xiàn)Runnable接口,此接口只有一個函數(shù),run(),此函數(shù)必須由實(shí)現(xiàn)了此接口的類實(shí)現(xiàn)。
       
        例如: 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();
          }
        }

        兩種創(chuàng)建方式差別不大,第一種因?yàn)槔^承自Thread,只創(chuàng)建了自身對象,第二種還得創(chuàng)建Thread對象.但是當(dāng)你想繼承某一其它類時,你只能用后一種方式.大多數(shù)人偏愛后一種的原因大概也在于此吧.

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

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

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

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

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

    public int synMethod(int a1){
            synchronized(a1) {
              //一次只能有一個線程進(jìn)入
            }
          }
        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,如果線程進(jìn)入,則得到當(dāng)前對象鎖,那么別的線程在該類所有對象上的任何操作都不能進(jìn)行.在對象級使用鎖通常是一種比較粗糙的方法。為什么要將整個對象都上鎖,而不允許其他線程短暫地使用對象中其他同步方法來訪問共享資源?如果一個對象擁有多個資源,就不需要只為了讓一個線程使用其中一部分資源,就將所有線程都鎖在外面。由于每個對象都有鎖,可以如下所示使用虛擬對象來上鎖: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++;             // 鎖數(shù)加 1。
          lock_order = num_locks;  // 為此對象實(shí)例設(shè)置唯一的 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;       // 保留數(shù)組引用的一個
        ArrayWithLockOrder last = a2;        // 本地副本。
        int size = a1.array().length;
        if (size == a2.array().length)
        {
          if (a1.lockOrder() > a2.lockOrder())  // 確定并設(shè)置對象的鎖定
          {                                     // 順序。
            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,如果線程進(jìn)入,則線程在該類中所有操作不能進(jìn)行,包括靜態(tài)變量和靜態(tài)方法,實(shí)際上,對于含有靜態(tài)方法和靜態(tài)變量的代碼塊的同步,我們通常用4來加鎖.

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

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

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

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

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

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

        其實(shí)用生產(chǎn)者/消費(fèi)者這個例子最好說明他們之間的關(guān)系了:

        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);
        }
        }
      }
           生產(chǎn)者生產(chǎn),消費(fèi)者消費(fèi),一般沒有沖突,但當(dāng)庫存為0時,消費(fèi)者要消費(fèi)是不行的,但當(dāng)庫存為上限(這里是10)時,生產(chǎn)者也不能生產(chǎn).請好好研讀上面的程序,你一定會比以前進(jìn)步很多.

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

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

    posted on 2005-06-24 13:48 蘋果 閱讀(364) 評論(0)  編輯  收藏 所屬分類: J2EE/JAVA學(xué)習(xí)
    主站蜘蛛池模板: 国产精品久久免费视频| 日本zzzzwww大片免费| 免费国产不卡午夜福在线 | 亚洲爱情岛论坛永久| 最近中文字幕大全免费版在线| 亚洲最大激情中文字幕| 在线免费观看伊人三级电影| 亚洲综合色婷婷七月丁香| 成人av片无码免费天天看| 精品久久久久久亚洲| 99久久免费观看| 亚洲性无码av在线| 野花高清在线观看免费3中文| 亚洲乱亚洲乱妇无码| 又大又黄又粗又爽的免费视频| 一本到卡二卡三卡免费高| 亚洲男人天堂av| 99久久精品日本一区二区免费| 亚洲av片在线观看| 久久国产成人亚洲精品影院| 免费精品一区二区三区第35| 久久精品国产亚洲av麻豆图片| 天天操夜夜操免费视频| 一级视频在线免费观看| 亚洲AV无码不卡在线播放| 成年在线观看网站免费| 黄色毛片免费观看| 中文字幕在线观看亚洲| 香蕉视频在线观看免费国产婷婷 | 久久福利青草精品资源站免费| 亚洲天天做日日做天天欢毛片| 久久久久国产精品免费免费搜索| 色妞www精品视频免费看| 亚洲资源在线观看| 国产女高清在线看免费观看| 在线观看肉片AV网站免费| 香蕉大伊亚洲人在线观看| 国产亚洲成AV人片在线观黄桃 | 亚洲精品久久久www| 5555在线播放免费播放| 美女被艹免费视频|