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

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

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

    Picses' sky

    Picses' sky
    posts - 43, comments - 29, trackbacks - 0, articles - 24

    java線程簡(jiǎn)單介紹[zz]

    Posted on 2007-07-18 10:55 Matthew Chen 閱讀(690) 評(píng)論(2)  編輯  收藏 所屬分類: Java MultiThread

    在java中,一個(gè)線程用一個(gè)Thread對(duì)象表示
    一般每一個(gè)java程序都有一個(gè)main方法(applet沒(méi)有),它是主線程的入口點(diǎn)
    而用Thread表示的線程,入口點(diǎn)自然不是main了,而是run方法
    定義一個(gè)線程,主要就是寫(xiě)它的run方法
    寫(xiě)run有兩種方法,一種是繼承Thread類,然后重寫(xiě)它的run
    另一種是實(shí)現(xiàn)Runnable接口,然后重寫(xiě)它的run,如下所示:
    ============================
    //用外部類實(shí)現(xiàn)多線程
    class  ThreadTest2
    {
     public static void main(String[] args)
     {
      new ThreadTest2();
     }
     ThreadTest2(){
      for(int i=1; i<=5; i++){
       System.out.println("creating thread "+i);
       outterThread th = new outterThread(i);//創(chuàng)建新線程
       th.start();//啟動(dòng)剛創(chuàng)建的線程
      }
     }
    }

    class outterThread extends Thread//通過(guò)繼承Thread類來(lái)實(shí)現(xiàn)多線程;外部類
    {
     int count;
     outterThread(int i){
      count = i;
     }
     public void run() {
      while(true){
       System.out.println("thread "+count+" is running");
       try{
        sleep(1000*count);
       }
       catch(InterruptedException e){}
      }
     }
    }
    =====================================
    class ThreadTest3 implements Runnable //通過(guò)實(shí)現(xiàn)Runnable接口來(lái)實(shí)現(xiàn)多線程
    {
     int count;
     public static void main(String[] args)
     {
      for(int i=1; i<=5; i++)
       //調(diào)用了Thread類的構(gòu)造函數(shù)Thread(Runnable target)
       new Thread(new ThreadTest3(i)).start();
     }
     ThreadTest3(int i){
      System.out.println("creating thread "+i);
      count = i;
     }
     public void run(){
      while(true){
       System.out.println("thread "+count+" is running");
       try{
        Thread.sleep(1000*count);//讓線程睡眠一段時(shí)間
       }
       catch(InterruptedException e){}
      }
     }
    }
    可以看到,不論如何重寫(xiě)run,都要生成Thread對(duì)象.不同的是,第二種方法要在Thread的構(gòu)造函數(shù)里傳入Runnable的實(shí)現(xiàn)類作為參數(shù)
    上面的例子還用到了start()和sleep()
    前者用作啟動(dòng)線程,調(diào)用它之后,run方法就開(kāi)始執(zhí)行;后者使線程暫停參數(shù)指定的時(shí)間,單位是毫秒.這個(gè)sleep會(huì)拋出異常,所以要有try,catch塊
    ===========================
    在上面的例子中,在for循環(huán)中創(chuàng)建的線程和主線程是并列的,一個(gè)線程的結(jié)束不會(huì)影響另一個(gè)線程
    在上面的例子中,執(zhí)行完for循環(huán),主線程就結(jié)束了,而其他線程還在運(yùn)行著
    用setDaemon()可以使一個(gè)線程作為后臺(tái)線程執(zhí)行,也就是說(shuō),當(dāng)其他非Daemon線程結(jié)束時(shí),不論run執(zhí)行完沒(méi)有,后臺(tái)線程也將退出
    反過(guò)來(lái),你也可以使主線程等待其他線程結(jié)束后再退出.注意這里是主線程等待其他線程結(jié)束,而上面講的daemon線程是在所有非daemon(主線程和其他非daemon)退出后再退出.要實(shí)現(xiàn)這一目的,可使用join().它可帶可不帶參數(shù),帶參數(shù)的話, 參數(shù)表示等待時(shí)間,如果過(guò)了這指定的時(shí)間不管join了的線程退出與否,主線程都會(huì)結(jié)束(如果main方法已經(jīng)執(zhí)行完了)
    下面是例子
    =======================
    class DaemonAndJoin
    {
     public static void main(String[] args)
     {
      Thread th = new Thread( new Runnable(){ 
       int count = 2;
       public void run(){
        while(count>0){
         for(int i=0; i<5; i++){
          try{
           Thread.sleep(500);
           System.out.println("in thread 1 ");
          }catch(InterruptedException e){
           e.printStackTrace();
          }
         }
         count--;
         System.out.println("one for is done");
        }
       }
      });
      Thread th2 = new Thread(new Runnable(){
       public void run(){
        while(true){
         try{
          Thread.sleep(1000);
          System.out.println("in thread 2");
         }catch(InterruptedException e){
          e.printStackTrace();
         }
        }
       }
      });
      System.out.println("main thread begins");  
      th.start(); 
      th2.setDaemon(true);//設(shè)置后臺(tái)線程
      th2.start();
      try{
       th.join();//join
      }catch(InterruptedException e){
       e.printStackTrace();
      }
      System.out.println("main thread quits");
     }
    }
    ==============
    上面例子,如果沒(méi)有th這個(gè)線程,th2和主線程都會(huì)很快結(jié)束
    如果有th,但是沒(méi)有join,主線程會(huì)很快結(jié)束,但是th2因?yàn)檫€有一個(gè)非daemon未結(jié)束,所以不會(huì)很快結(jié)束,而一直等到th結(jié)束才結(jié)束
    如果沒(méi)有setDaemon,則th不影響th2
    ==================
    線程的同步
    當(dāng)多個(gè)線程同時(shí)對(duì)一個(gè)對(duì)象進(jìn)行操作,就有可能發(fā)生問(wèn)題,這時(shí)就要用線程同步來(lái)解決
    考慮下面的例子
    class SychronizedTest
    {
     public static void main(String[] args)
     {
      final Student stu = new Student();
      Thread setNameAndNumth1 = new Thread( new Runnable(){
       public void run(){
        while(true){
         synchronized(stu){
          stu.setNameAndNum("john","jj");
         }
        }
       }
      });
      Thread setNameAndNumth2 = new Thread( new Runnable(){
       public void run(){
        while(true){
         //synchronized(stu){
          stu.setNameAndNum("kate","kk");
         //}
        }
       }
      });
      setNameAndNumth1.start();
      setNameAndNumth2.start();
      System.out.println("test started:");
     }
    }
    class Student{
     private String name;
     private String id;
     private int count = 0;
     public /*synchronized*/ void setNameAndNum(String name,String id){
    //  synchronized(this){
       this.name = name;
       this.id = id;
       count++;
       if(!check())
        System.out.println( count + " unmatched name and id: "+name+" "+id);
    //  }
     }
     private boolean check(){
      return name.charAt(0) == id.charAt(0);
     }
    }
    在這個(gè)例子中,Student類有兩個(gè)屬性.
    有兩個(gè)線程,它們修改同一個(gè)Student類的實(shí)例,然后檢查修改后的這個(gè)實(shí)例的兩個(gè)屬性符不符合要求(判斷兩個(gè)屬性的第一個(gè)字符是否一樣)
    如果不符合要求,則在控制臺(tái)輸出語(yǔ)句,否則不輸出
    例子中有三部分注釋,每一部分說(shuō)明了一種同步方式
    最上面方式使Student類的方法都按同步的方式執(zhí)行
    第二種通過(guò)synchronized關(guān)鍵字,使單一一個(gè)方法,而不是全部方法按同步的方式執(zhí)行
    第三種只是一個(gè)方法里的某一部分按同步的方法執(zhí)行(雖然在這個(gè)例子里,方法的整個(gè)方法體都被括起來(lái)了)
    ====================================
    最后附上經(jīng)典的生者消費(fèi)者程序
    class WaitNotifyTest
    {
     public static void main(String[] args)
     {
      Clerk clerk = new Clerk();
      Producer producer = new Producer(clerk);
      Consumer consumer = new Consumer(clerk);
      Thread producerThread = new Thread(producer);
      Thread consumerThread = new Thread(consumer);
      producerThread.start();
      consumerThread.start();
     }
    }
    class Producer implements Runnable{
     Clerk clerk;
     Producer(Clerk clerk){
      this.clerk = clerk;
     }
     public void run(){
      System.out.println("producer starts producing product " );
      for(int i=0; i<10; i++){
       try{
        Thread.sleep( (int)(Math.random()*3000) );
       }catch(InterruptedException e){
        e.printStackTrace();
       }
       clerk.setProduct(i);
    //   System.out.println("producer is producing product " + i);
       
      }
     }
    }
    class Consumer implements Runnable{
     Clerk clerk;
     Consumer(Clerk clerk){
      this.clerk = clerk;
     }
     public void run(){
      System.out.println("consumer starts consuming product " );
      for(int i=0; i<10; i++){
       try{
        Thread.sleep( (int)(Math.random()*3000) );
       }catch(InterruptedException e){
        e.printStackTrace();
       }
       clerk.getProduct();
    //   System.out.println("consumer is consuming product "+ i);
       
      }
     }
    }
    class Clerk{
     int product = -1;
     public synchronized void setProduct(int product){
      if( this.product != -1  ){
       try{  
         wait();
        }catch(InterruptedException e){
         e.printStackTrace();
        }
      }
      this.product = product;
      System.out.println("producer is producing product " + product);
      notify();
     }
     public synchronized void getProduct(){
      if( product == -1 ){
       try{
        wait();
       }catch(InterruptedException e){
        e.printStackTrace();
       }
      }
      System.out.println("consumer is consuming product "+ product);
      this.product = -1;
      notify();
     }

    Feedback

    # re: java線程簡(jiǎn)單介紹[zz]  回復(fù)  更多評(píng)論   

    2009-04-09 20:56 by huxianbao
    太有用了,呵呵

    # re: java線程簡(jiǎn)單介紹[zz]  回復(fù)  更多評(píng)論   

    2009-04-09 22:56 by huxianbao
    最后一個(gè)生產(chǎn)者-消費(fèi)者程序真的是太經(jīng)典了
    呵呵
    主站蜘蛛池模板: 老司机福利在线免费观看| 69视频免费观看l| 亚洲精品第一综合99久久| JLZZJLZZ亚洲乱熟无码| 成人毛片免费在线观看| 久久免费观看国产精品88av| 色多多A级毛片免费看| 亚洲日韩精品无码专区加勒比☆| 久久久无码精品亚洲日韩按摩| 亚洲精品天堂成人片?V在线播放| 色视频色露露永久免费观看| 国产大片免费网站不卡美女| 久爱免费观看在线网站| 国产综合免费精品久久久| 男女超爽视频免费播放| 亚洲AV噜噜一区二区三区| 亚洲乱码一二三四区乱码| 亚洲最大视频网站| 亚洲精品网站在线观看你懂的| 亚洲成A人片在线观看WWW| 国产亚洲?V无码?V男人的天堂| 又粗又硬免费毛片| 免费永久在线观看黄网站| 免费无码黄动漫在线观看| 天天摸天天碰成人免费视频| 久久国内免费视频| 久久这里只有精品国产免费10| 国产大片91精品免费观看不卡| 2020因为爱你带字幕免费观看全集 | 国产亚洲成av片在线观看| 在线精品亚洲一区二区三区| 伊人久久精品亚洲午夜| 亚洲一区精品无码| 亚洲熟妇无码乱子AV电影| 国产精品亚洲а∨无码播放| 国产亚洲精品精华液| 亚洲视频精品在线| 亚洲午夜电影在线观看高清 | 91久久精品国产免费直播| 在线视频免费观看爽爽爽| 99re热免费精品视频观看 |