posts - 3, comments - 1, trackbacks - 0, articles - 5
          關(guān)于 java多線程學(xué)習(xí)總結(jié)
          小弟的第二篇j2se學(xué)習(xí)筆記,如果有錯(cuò)誤或者遺漏的地方,還懇請(qǐng)各位高手老鳥們不要見笑,多給小弟一些批評(píng),建議!

          一、線程的基本概念
          簡(jiǎn)單的說(shuō):線程就是一個(gè)程序里不同的執(zhí)行路徑
          在同一個(gè)時(shí)間點(diǎn)上cpu只會(huì)有一個(gè)線程在執(zhí)行
          Java里的多線程是通過(guò)java.lang.Thread類來(lái)實(shí)現(xiàn)的
          每個(gè)線程都擁有自己獨(dú)立的方法??臻g

          二、java線程的創(chuàng)建和啟動(dòng)
          第一種
           定義線程類實(shí)現(xiàn)Runnable接口
           Thread myThread = new Thread(target) //target為Runnable接口類型
           Runnable中只有一個(gè)方法:
           public void run();用以定義線程運(yùn)行體
          第二種
           可以定義一個(gè)Thread的子類并重寫其run方法:
            clas MyThread extends Thread{
             public void run(){}
            }
          線程類必須通過(guò)執(zhí)行Thread的start()方法啟動(dòng)一個(gè)新的線程
          如果調(diào)用run()方法是屬于方法的調(diào)用,不會(huì)啟動(dòng)一個(gè)新的線程
          推薦使用第一種方式創(chuàng)建線程,使用接口較為靈活

          二、線程狀態(tài)裝換
          調(diào)用線程start()方法時(shí),線程進(jìn)入就緒狀態(tài),Cpu分配時(shí)間片,線程進(jìn)入運(yùn)行狀態(tài)
          時(shí)間片結(jié)束,run()方法未執(zhí)行完,線程進(jìn)入阻塞狀態(tài)。

          三、線程控制基本方法
           isAlive() //判斷線程是否還“活著”,即線程是否還未終止
           getPriority() //獲得線程的優(yōu)先級(jí)數(shù)值
           setPriority() //設(shè)置線程的優(yōu)先級(jí)指數(shù)
           Thread.sleep() //靜態(tài)方法,將當(dāng)前線程睡眠指定毫秒數(shù)
           join()  //調(diào)用某線程的該方法,將當(dāng)前線程與該線程合并,
             //即等待該線程結(jié)束,再回復(fù)當(dāng)前線程的運(yùn)行。
           yield()  //讓出CPU,當(dāng)前線程進(jìn)入就緒狀態(tài)等待調(diào)度
           interrupt() //中斷線程
           wait()  //當(dāng)前線程進(jìn)入對(duì)象的wait pool
           notify()/all //喚醒對(duì)象的wait pool中的一個(gè)/所有等待線程

          四、sleep方法
           Thread的靜態(tài)方法
           public static void sleep(long millis)throws InterruptedException
           必須對(duì)異常進(jìn)行捕捉
           Thread.currentThread();  //拿到當(dāng)前線程

          五、interrupt方法一種讓線程退出的方式。

          import java.util.*;
          public class TestInterrupt{
              
          public static void main(String[] args){
                  MyThread t 
          = new MyThread();
                  t.start();
                  
          try{Thread.sleep(10000);}
                  
          catch(InterruptedException i){}
                  t.interrupt();
              }
          }

          class MyThread extends Thread{
              
          public void run(){
                  
          while(true){
                      
          try{
                          System.out.println(
          "------"+new Date()+"-----");
                          Thread.sleep(
          1000);
                      }
          catch(InterruptedException i){
                          
          return;
                      }
                  }
              }
          }


          六、join和yield方法 
           t.join(); //t的run()方法完才會(huì)繼續(xù)執(zhí)行當(dāng)前線程方法體
             //也就是兩個(gè)線程變成了一個(gè)線程
           t.yield(); //暫停當(dāng)前正在執(zhí)行的線程對(duì)象,并執(zhí)行其他線程。方法為靜態(tài)
             //哪個(gè)線程體執(zhí)行此方法,哪個(gè)線程讓步

          public class TestYield {
            
          public static void main(String[] args) {
              MyThread3 t1 
          = new MyThread3("t1");
              MyThread3 t2 
          = new MyThread3("t2");
              t1.start(); t2.start();
            }
          }
          class MyThread3 extends Thread {
            MyThread3(String s){
          super(s);}
            
          public void run(){
              
          for(int i =1;i<=100;i++){
                System.out.println(getName()
          +""+i);
                
          if(i%10==0){
                  yield();
                }
              }
            }
          }


          七、線程優(yōu)先級(jí)別 
           線程的優(yōu)先級(jí)用數(shù)字表示,范圍從1到10,一個(gè)線程的缺省優(yōu)先級(jí)為5.
           Thread.MAX_PRIORITY=1
           Thread.MIN_PRIORITY=10
           Thread.NORM_PRIORITY=5
           例:t.setPriority(Thread.NORM_PRIORITY+3);
           
          ★八、線程同步
           1.同步代碼塊
           synchronized(this){  //在執(zhí)行代碼塊過(guò)程中,不會(huì)被其他線程打斷
            ...  
           }
           public sunchronized void method //執(zhí)行此方法時(shí),當(dāng)前對(duì)象被鎖定
           在Java語(yǔ)言中,引入了對(duì)象互斥鎖的概念,保證共享數(shù)據(jù)操作的完整性,每個(gè)對(duì)象 都對(duì)應(yīng)一個(gè)可稱為"互斥鎖"的標(biāo)記,這個(gè)標(biāo)記保證在任一時(shí)刻,只能有一個(gè)線程訪 問(wèn)該對(duì)象。
           2.線程死鎖

          public class TestDeadLock implements Runnable {
              
          public int flag = 1;
              
          static Object o1 = new Object(), o2 = new Object();
              
          public void run() {
          System.out.println(
          "flag=" + flag);
                  
          if(flag == 1) {
                      
          synchronized(o1) {
                          
          try {
                              Thread.sleep(
          500);
                          } 
          catch (Exception e) {
                              e.printStackTrace();
                          }
                          
          synchronized(o2) {
                              System.out.println(
          "1");    
                          }
                      }
                  }
                  
          if(flag == 0) {
                      
          synchronized(o2) {
                          
          try {
                              Thread.sleep(
          500);
                          } 
          catch (Exception e) {
                              e.printStackTrace();
                          }
                          
          synchronized(o1) {
                              System.out.println(
          "0");
                          }
                      }
                  }
              }    
              
              
          public static void main(String[] args) {
                  TestDeadLock td1 
          = new TestDeadLock();
                  TestDeadLock td2 
          = new TestDeadLock();
                  td1.flag 
          = 1;
                  td2.flag 
          = 0;
                  Thread t1 
          = new Thread(td1);
                  Thread t2 
          = new Thread(td2);
                  t1.start();
                  t2.start();
                  
              }
          }


          九、生產(chǎn)者消費(fèi)者問(wèn)題

          public class ProducerConsumer {
              
          public static void main(String[] args) {
                  SyncStack ss 
          = new SyncStack();
                  Producer p 
          = new Producer(ss);
                  Consumer c 
          = new Consumer(ss);
                  
          new Thread(p).start();
                  
          new Thread(p).start();
                  
          new Thread(p).start();
                  
          new Thread(c).start();
              }
          }

          class WoTou {
              
          int id; 
              WoTou(
          int id) {
                  
          this.id = id;
              }
              
          public String toString() {
                  
          return "WoTou : " + id;
              }
          }

          class SyncStack {        //棧實(shí)現(xiàn)
              int index = 0;
              WoTou[] arrWT 
          = new WoTou[6];    //相當(dāng)于裝物品的籃子
              
              
          public synchronized void push(WoTou wt) {    //生產(chǎn)物品,線程安全
                  while(index == arrWT.length) {        //當(dāng)籃子滿了線程等待
                      try {            
                          
          this.wait();        
                      } 
          catch (InterruptedException e) {
                          e.printStackTrace();
                      }
                      
                  }
                  
          this.notifyAll();    //開始生產(chǎn)時(shí),叫醒等待的其他線程開始消費(fèi)
                  arrWT[index] = wt;    
                  index 
          ++;
              }
              
              
          public synchronized WoTou pop() {        //消費(fèi)物品,線程安全
                  while(index == 0) {            //如果籃子空了
                      try {
                          
          this.wait();        //線程等待,等待生產(chǎn)者開始                            //生產(chǎn),叫醒此線程
                      } catch (InterruptedException e) {
                          e.printStackTrace();
                      }
                      
                  }
                  
          this.notifyAll();            //消費(fèi)時(shí)喊醒生產(chǎn)者生產(chǎn)
                  index--;
                  
          return arrWT[index];
              }
          }

          class Producer implements Runnable {            //生產(chǎn)者類
              SyncStack ss = null;
              Producer(SyncStack ss) {
                  
          this.ss = ss;
              }
              
              
          public void run() {
                  
          for(int i=0; i<20; i++) {    //生產(chǎn)20個(gè)
                      WoTou wt = new WoTou(i);
                      ss.push(wt);            
                      System.out.println(
          "生產(chǎn)了:" + wt);
                      
          try {
                          Thread.sleep((
          int)(Math.random() * 200));
                      } 
          catch (InterruptedException e) {
                          e.printStackTrace();
                      }            
                  }
              }
          }

          class Consumer implements Runnable {
              SyncStack ss 
          = null;
              Consumer(SyncStack ss) {
                  
          this.ss = ss;
              }
              
              
          public void run() {
                  
          for(int i=0; i<20; i++) {        //消費(fèi)20個(gè)
                      WoTou wt = ss.pop();
                      System.out.println(
          "消費(fèi)了: " + wt);
                      
          try {
                          Thread.sleep((
          int)(Math.random() * 1000));
                      } 
          catch (InterruptedException e) {
                          e.printStackTrace();
                      }            
                  }
              }
          }

          Feedback

          # re: java多線程學(xué)習(xí)總結(jié)  回復(fù)  更多評(píng)論   

          2012-07-26 10:35 by 啊啊啊
          垃圾?。?!

          沒(méi)有一點(diǎn)兒自己的看法!!~~~

          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 台北县| 宾川县| 贵州省| 肃宁县| 江门市| 商丘市| 应用必备| 长垣县| 平凉市| 隆化县| 闽清县| 宁津县| 自贡市| 静宁县| 南华县| 敦煌市| 军事| 长顺县| 马公市| 香格里拉县| 宜春市| 罗源县| 苏尼特右旗| 房产| 瓦房店市| 皮山县| 隆回县| 曲周县| 昌都县| 盐城市| 武冈市| 延庆县| 揭西县| 柏乡县| 塔河县| 东兰县| 米林县| 尼勒克县| 乌兰察布市| 钦州市| 博罗县|