hk2000c技術(shù)專欄

          技術(shù)源于哲學(xué),哲學(xué)來源于生活 關(guān)心生活,關(guān)注健康,關(guān)心他人

            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            111 隨筆 :: 1 文章 :: 28 評(píng)論 :: 0 Trackbacks

              一種是繼承自Thread類.Thread 類是一個(gè)具體的類,即不是抽象類,該類封裝了線程的行為。要?jiǎng)?chuàng)建一個(gè)線程,程序員必須創(chuàng)建一個(gè)從 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接口,此接口只有一個(gè)函數(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)建方式看起來差別不大,但是弄不清楚的話,也許會(huì)將你的程序弄得一團(tuán)糟。兩者區(qū)別有以下幾點(diǎn):

          1.當(dāng)你想繼承某一其它類時(shí),你只能用后一種方式.

          2.第一種因?yàn)槔^承自Thread,只創(chuàng)建了自身對(duì)象,但是在數(shù)量上,需要幾個(gè)線程,就得創(chuàng)建幾個(gè)自身對(duì)象;第二種只創(chuàng)建一個(gè)自身對(duì)象,卻創(chuàng)建幾個(gè)Thread對(duì)象.而兩種方法重大的區(qū)別就在于此,請(qǐng)你考慮:如果你在第一種里創(chuàng)建數(shù)個(gè)自身對(duì)象并且start()后,你會(huì)發(fā)現(xiàn)好像synchronized不起作用了,已經(jīng)加鎖的代碼塊或者方法居然同時(shí)可以有幾個(gè)線程進(jìn)去,而且同樣一個(gè)變量,居然可以有好幾個(gè)線程同時(shí)可以去更改它。(例如下面的代碼)這是因?yàn)椋谶@個(gè)程序中,雖然你起了數(shù)個(gè)線程,可是你也創(chuàng)建了數(shù)個(gè)對(duì)象,而且,每個(gè)線程對(duì)應(yīng)了每個(gè)對(duì)象也就是說,每個(gè)線程更改和占有的對(duì)象都不一樣,所以就出現(xiàn)了同時(shí)有幾個(gè)線程進(jìn)入一個(gè)方法的現(xiàn)象,其實(shí),那也不是一個(gè)方法,而是不同對(duì)象的相同的方法。所以,這時(shí)候你要加鎖的話,只能將方法或者變量聲明為靜態(tài),將static加上后,你就會(huì)發(fā)現(xiàn),線程又能管住方法了,同時(shí)不可能有兩個(gè)線程進(jìn)入同樣一個(gè)方法,那是因?yàn)椋F(xiàn)在不是每個(gè)對(duì)象都擁有一個(gè)方法了,而是所有的對(duì)象共同擁有一個(gè)方法,這個(gè)方法就是靜態(tài)方法。

              而你如果用第二種方法使用線程的話,就不會(huì)有上述的情況,因?yàn)榇藭r(shí),你只創(chuàng)建了一個(gè)自身對(duì)象,所以,自身對(duì)象的屬性和方法對(duì)于線程來說是共有的。

              因此,我建議,最好用后一種方法來使用線程。

          public class mainThread extends Thread{
            int i=0;
            public static void main(String args[]){
              mainThread m1 = new mainThread();
              mainThread m2 = new mainThread();
              mainThread m3 = new mainThread();
              mainThread m4 = new mainThread();
              mainThread m5 = new mainThread();
              mainThread m6 = new mainThread();
              m1.start();
              m2.start();
              m3.start();
              m4.start();
              m5.start();
              m6.start();
            }
            public synchronized void t1(){
              i=++i;
              try{
                Thread.sleep(500);
              }
              catch(Exception e){}
              //每個(gè)線程都進(jìn)入各自的t1()方法,分別打印各自的i
              System.out.println(Thread.currentThread().getName()+" "+i);
            }
            public void run(){
              synchronized(this){
                while (true) {
                  t1();
                }
              }
            }
          }

           

           


           

           

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

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

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

              2.對(duì)某一代碼塊使用,synchronized后跟括號(hào),括號(hào)里是變量,這樣,一次只有一個(gè)線程進(jìn)入該代碼塊.例如:

                public int synMethod(int a1){
                  synchronized(a1) {
                    //一次只能有一個(gè)線程進(jìn)入
                  }
                }
              3.synchronized后面括號(hào)里是一對(duì)象,此時(shí),線程獲得的是對(duì)象鎖.例如:

          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());
              }
            }
          }


           
              對(duì)于3,如果線程進(jìn)入,則得到對(duì)象鎖,那么別的線程在該類所有對(duì)象上的任何操作都不能進(jìn)行.在對(duì)象級(jí)使用鎖通常是一種比較粗糙的方法。為什么要將整個(gè)對(duì)象都上鎖,而不允許其他線程短暫地使用對(duì)象中其他同步方法來訪問共享資源?如果一個(gè)對(duì)象擁有多個(gè)資源,就不需要只為了讓一個(gè)線程使用其中一部分資源,就將所有線程都鎖在外面。由于每個(gè)對(duì)象都有鎖,可以如下所示使用虛擬對(duì)象來上鎖:

          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后面括號(hào)里是類.例如:

          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;  // 為此對(duì)象實(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ù)組引用的一個(gè)
              ArrayWithLockOrder last = a2;        // 本地副本。
              int size = a1.array().length;
              if (size == a2.array().length)
              {
                if (a1.lockOrder() > a2.lockOrder())  // 確定并設(shè)置對(duì)象的鎖定
                {                                     // 順序。
                  first = a2;
                  last = a1;
                }
                synchronized(first) {              // 按正確的順序鎖定對(duì)象。
                  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() {
              //...
            }
          }

           

              對(duì)于4,如果線程進(jìn)入,則線程在該類中所有操作不能進(jìn)行,包括靜態(tài)變量和靜態(tài)方法,實(shí)際上,對(duì)于含有靜態(tài)方法和靜態(tài)變量的代碼塊的同步,我們通常用4來加鎖.

          以上4種之間的關(guān)系:

              鎖是和對(duì)象相關(guān)聯(lián)的,每個(gè)對(duì)象有一把鎖,為了執(zhí)行synchronized語句,線程必須能夠獲得synchronized語句中表達(dá)式指定的對(duì)象的鎖,一個(gè)對(duì)象只有一把鎖,被一個(gè)線程獲得之后它就不再擁有這把鎖,線程在執(zhí)行完synchronized語句后,將獲得鎖交還給對(duì)象。
              在方法前面加上synchronized修飾符即可以將一個(gè)方法聲明為同步化方法。同步化方法在執(zhí)行之前獲得一個(gè)鎖。如果這是一個(gè)類方法,那么獲得的鎖是和聲明方法的類相關(guān)的Class類對(duì)象的鎖。如果這是一個(gè)實(shí)例方法,那么此鎖是this對(duì)象的鎖。

           


           

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

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

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

           


           

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

          1.有synchronized的地方不一定有wait,notify

          2.有wait,notify的地方必有synchronized.這是因?yàn)閣ait和notify不是屬于線程類,而是每一個(gè)對(duì)象都具有的方法,而且,這兩個(gè)方法都和對(duì)象鎖有關(guān),有鎖的地方,必有synchronized。

          另外,請(qǐng)注意一點(diǎn):如果要把notify和wait方法放在一起用的話,必須先調(diào)用notify后調(diào)用wait,因?yàn)槿绻{(diào)用完wait,該線程就已經(jīng)不是current thread了。如下例:

          /**
           * Title:        Jdeveloper's Java Projdect
           * Description:  n/a
           * Copyright:    Copyright (c) 2001
           * Company:      soho  http://www.ChinaJavaWorld.com
           * @author jdeveloper@21cn.com
           * @version 1.0
           */
          import java.lang.Runnable;
          import java.lang.Thread;

          public class DemoThread
              implements Runnable {

            public DemoThread() {
              TestThread testthread1 = new TestThread(this, "1");
              TestThread testthread2 = new TestThread(this, "2");

              testthread2.start();
              testthread1.start();

            }

            public static void main(String[] args) {
              DemoThread demoThread1 = new DemoThread();

            }

            public void run() {

              TestThread t = (TestThread) Thread.currentThread();
              try {
                if (!t.getName().equalsIgnoreCase("1")) {
                  synchronized (this) {
                    wait();
                  }
                }
                while (true) {

                  System.out.println("@time in thread" + t.getName() + "=" +
                                     t.increaseTime());

                  if (t.getTime() % 10 == 0) {
                    synchronized (this) {
                      System.out.println("****************************************");
                      notify();
                      if (t.getTime() == 100)
                        break;
                      wait();
                    }
                  }
                }
              }
              catch (Exception e) {
                e.printStackTrace();
              }
            }

          }

          class TestThread
              extends Thread {
            private int time = 0;
            public TestThread(Runnable r, String name) {
              super(r, name);
            }

            public int getTime() {
              return time;
            }

            public int increaseTime() {
              return++time;
            }

          }

              下面我們用生產(chǎn)者/消費(fèi)者這個(gè)例子來說明他們之間的關(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時(shí),消費(fèi)者要消費(fèi)是不行的,但當(dāng)庫存為上限(這里是10)時(shí),生產(chǎn)者也不能生產(chǎn).請(qǐng)好好研讀上面的程序,你一定會(huì)比以前進(jìn)步很多.

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

           
          posted on 2008-01-02 18:14 hk2000c 閱讀(371) 評(píng)論(0)  編輯  收藏 所屬分類: Java 技術(shù)
          主站蜘蛛池模板: 当阳市| 曲松县| 津市市| 闵行区| 济宁市| 收藏| 曲松县| 曲周县| 彰化县| 桐庐县| 资阳市| 潼关县| 武山县| 清水河县| 通城县| 米易县| 宾川县| 托里县| 新和县| 陇川县| 大渡口区| 比如县| 登封市| 定襄县| 千阳县| 安化县| 盐城市| 闻喜县| 迭部县| 文登市| 徐汇区| 彰化县| 闽侯县| 沈阳市| 洛隆县| 聂拉木县| 南和县| 卫辉市| 武宁县| 华亭县| 罗平县|