首頁  >  文章  >  Java  >  Java中有關多執行緒的使用詳解

Java中有關多執行緒的使用詳解

黄舟
黄舟原創
2017-09-08 11:15:151170瀏覽

這篇文章主要介紹了Java多線程的用法詳細介紹的相關資料,希望透過本文能幫助到大家,需要的朋友可以參考下

Java多線程的用法詳細介紹

最全面的Java多執行緒用法解析,如果你對Java的多執行緒機制並沒有深入的研究,那麼本文可以幫助你更透徹地理解Java多執行緒的原理以及使用方法。

1.建立執行緒

在Java中建立執行緒有兩種方法:使用Thread類別和使用Runnable介面。使用Runnable介面時需要建立一個Thread實例。因此,無論是透過Thread類別或Runnable介面建立線程,都必須建立Thread類別或它的子類別的實例。 Thread建構子:


public Thread( );
public Thread(Runnable target);
public Thread(String name);
public Thread(Runnable target, String name);
public Thread(ThreadGroup group, Runnable target);
public Thread(ThreadGroup group, String name);
public Thread(ThreadGroup group, Runnable target, String name);
public Thread(ThreadGroup group, Runnable target, String name, long stackSize);

方法一:繼承Thread類別覆寫run方法


public class ThreadDemo1 {
   public static void main(String[] args){
     Demo d = new Demo();
     d.start();
     for(int i=0;i<60;i++){
       System.out.println(Thread.currentThread().getName()+i);
     }

   }
 }
 class Demo extends Thread{
   public void run(){
     for(int i=0;i<60;i++){
       System.out.println(Thread.currentThread().getName()+i);
     }
   }
 }

方法二:


public class ThreadDemo2 {
  public static void main(String[] args){
    Demo2 d =new Demo2();
    Thread t = new Thread(d);
    t.start();
    for(int x=0;x<60;x++){
      System.out.println(Thread.currentThread().getName()+x);
    }
  }
}
class Demo2 implements Runnable{
  public void run(){
    for(int x=0;x<60;x++){
      System.out.println(Thread.currentThread().getName()+x);
    }
  }
}

2.執行緒的生命週期

與人有生老病死一樣,執行緒也同樣要經歷開始(等待)、運行、掛起和停止四種不同的狀態。這四種狀態都可以透過Thread類別中的方法進行控制。下面給出了Thread類別中和這四種狀態相關的方法。


// 开始线程
publicvoid start( );
publicvoid run( );
// 挂起和唤醒线程
publicvoid resume( );   // 不建议使用
publicvoid suspend( );  // 不建议使用
publicstaticvoid sleep(long millis);
publicstaticvoid sleep(long millis, int nanos);
// 终止线程
publicvoid stop( );    // 不建议使用
publicvoid interrupt( );
// 得到线程状态
publicboolean isAlive( );
publicboolean isInterrupted( );
publicstaticboolean interrupted( );
// join方法
publicvoid join( ) throws InterruptedException;

執行緒在建立後並不會馬上執行run方法中的程式碼,而是處於等待狀態。當執行緒處於等待狀態時,可以透過Thread類別的方法來設定執行緒不各種屬性,如執行緒的優先權(setPriority)、執行緒名(setName)和執行緒的類型(setDaemon)等。

當呼叫start方法後,執行緒開始執行run方法中的程式碼。執行緒進入運行狀態。可以透過Thread類別的isAlive方法來判斷執行緒是否處於運行狀態。當執行緒處於運行狀態時,isAlive傳回true,當isAlive回傳false時,可能執行緒處於等待狀態,也可能處於停止狀態。下面的程式碼示範了執行緒的建立、運行和停止三個狀態之間的切換,並輸出了對應的isAlive回傳值。

一但執行緒開始執行run方法,就會一直到這個run方法執行完成這個執行緒才退出。但在執行緒執行的過程中,可以透過兩個方法使執行緒暫時停止執行。這兩個方法是suspend和sleep。使用suspend掛起執行緒後,可以透過resume方法喚醒執行緒。而使用sleep讓執行緒休眠後,只能在設定的時間後讓執行緒處於就緒狀態(在執行緒休眠結束後,執行緒不一定會馬上執行,只是進入了就緒狀態,等待系統進行調度)。

在使用sleep方法時有兩點需要注意:

1. sleep方法有兩個重載形式,其中一個重載形式不僅可以設毫秒,而且還可以設納秒(1,000,000奈秒等於1毫秒)。但大多數作業系統平台上的Java虛擬機都無法精確到奈秒,因此,如果對sleep設定了奈秒,Java虛擬機將取最接近這個值的毫秒。

2. 使用sleep方法時必須使用throws或try{…}catch{…}。因為run方法無法使用throws,所以只能用try{…}catch{…}。當在執行緒休眠的過程中,使用interrupt方法中斷執行緒時sleep會拋出一個InterruptedException例外。 sleep方法的定義如下:


publicstaticvoid sleep(long millis) throws InterruptedException
publicstaticvoid sleep(long millis, int nanos) throws InterruptedException

有三種方法可以讓終止執行緒。

1.  使用退出標誌,讓執行緒正常退出,也就是run方法完成後執行緒終止。

2.  使用stop方法強行終止執行緒(這個方法不建議使用,因為stop和suspend、resume一樣,也可能發生不可預料的結果)。

3.  使用interrupt方法中斷執行緒。

1. 使用退出標誌終止執行緒

當run方法執行完後,執行緒就會退出。但有時run方法是永遠不會結束的。如在服務端程式中使用執行緒進行監聽客戶端請求,或是其他的需要循環處理的任務。在這種情況下,一般是將這些任務放在一個循環中,如while循環。如果想要讓迴圈永遠運作下去,可以使用while(true){…}來處理。但要使while循環在某一特定條件下退出,最直接的方法就是設一個boolean類型的標誌,並透過設定這個標誌為true或false來控制while循環是否退出。下面給了一個利用退出標誌終止執行緒的範例。

join方法的功能就是讓非同步執行的執行緒變成同步執行。也就是說,當呼叫執行緒實例的start方法後,這個方法會立即傳回,如果在呼叫start方法後後需要使用這個執行緒計算得到的值,就必須使用join方法。如果不使用join方法,就無法保證當執行到start方法後面的某條語句時,這個執行緒一定會執行完。而使用join方法後,直到這個執行緒退出,程式才會往下執行。下面的程式碼示範了join的用法。

3.多執行緒安全性問題

问题原因:当多条语句在操作同一个线程共享数据时,一个线程对多条语句只执行了一部分,还没执行完,另一个线程参与进来执行,导致共享数据的错误。

解决办法:对多条操作共享数据的语句,只能让一个线程都执行完,在执行过程中,其他线程不执行。

同步代码块:


public class ThreadDemo3 {
  public static void main(String[] args){
    Ticket t =new Ticket();
    Thread t1 = new Thread(t,"窗口一");
    Thread t2 = new Thread(t,"窗口二");
    Thread t3 = new Thread(t,"窗口三");
    Thread t4 = new Thread(t,"窗口四");
    t1.start();
    t2.start();
    t3.start();
    t4.start();
  }
}
class Ticket implements Runnable{
  private int ticket =400;
  public void run(){
    while(true){
      synchronized (new Object()) {
        try {
          Thread.sleep(1);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        if(ticket<=0)
          break;
        System.out.println(Thread.currentThread().getName()+"---卖出"+ticket--);
      }
    }
  }
}

同步函数


public class ThreadDemo3 {
  public static void main(String[] args){
    Ticket t =new Ticket();
    Thread t1 = new Thread(t,"窗口一");
    Thread t2 = new Thread(t,"窗口二");
    Thread t3 = new Thread(t,"窗口三");
    Thread t4 = new Thread(t,"窗口四");
    t1.start();
    t2.start();
    t3.start();
    t4.start();
  }
}
class Ticket implements Runnable{
  private int ticket = 4000;
  public synchronized void saleTicket(){
    if(ticket>0)
      System.out.println(Thread.currentThread().getName()+"卖出了"+ticket--);

  }
  public void run(){
    while(true){
      saleTicket();
    }
  }
}

同步函数锁是this 静态同步函数锁是class

线程间的通信


public class ThreadDemo3 {
  public static void main(String[] args){
    class Person{
      public String name;
      private String gender;
      public void set(String name,String gender){
        this.name =name;
        this.gender =gender;
      }
      public void get(){
        System.out.println(this.name+"...."+this.gender);
      }
    }
    final Person p =new Person();
    new Thread(new Runnable(){
      public void run(){
        int x=0;
        while(true){
          if(x==0){
            p.set("张三", "男");
          }else{
            p.set("lili", "nv");
          }
          x=(x+1)%2;
        }
      }
    }).start();
    new Thread(new Runnable(){
      public void run(){
        while(true){
          p.get();
        }
      }
    }).start();
  }
}
/*
张三....男
张三....男
lili....nv
lili....男
张三....nv
lili....男
*/

修改上面代码


public class ThreadDemo3 {
   public static void main(String[] args){
     class Person{
       public String name;
       private String gender;
       public void set(String name,String gender){
         this.name =name;
         this.gender =gender;
       }
       public void get(){
         System.out.println(this.name+"...."+this.gender);
       }
     }
     final Person p =new Person();
     new Thread(new Runnable(){
       public void run(){
         int x=0;
         while(true){
           synchronized (p) {
             if(x==0){
               p.set("张三", "男");
             }else{
               p.set("lili", "nv");
             }
             x=(x+1)%2;  
           }

         }
       }
     }).start();
     new Thread(new Runnable(){
       public void run(){
         while(true){
           synchronized (p) {
             p.get();
           }
         }
       }
     }).start();
   }

 }
 /*
 lili....nv
 lili....nv
 lili....nv
 lili....nv
 lili....nv
 lili....nv
 张三....男
 张三....男
 张三....男
 张三....男
 */

等待唤醒机制


/*
 *线程等待唤醒机制
 *等待和唤醒必须是同一把锁 
 */
public class ThreadDemo3 {
  private static boolean flags =false;
  public static void main(String[] args){
    class Person{
      public String name;
      private String gender;
      public void set(String name,String gender){
        this.name =name;
        this.gender =gender;
      }
      public void get(){
        System.out.println(this.name+"...."+this.gender);
      }
    }
    final Person p =new Person();
    new Thread(new Runnable(){
      public void run(){
        int x=0;
        while(true){
          synchronized (p) {
            if(flags)
              try {
                p.wait();
              } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              };
            if(x==0){
              p.set("张三", "男");
            }else{
              p.set("lili", "nv");
            }
            x=(x+1)%2;
            flags =true;
            p.notifyAll();
          }
        }
      }
    }).start();
    new Thread(new Runnable(){
      public void run(){
        while(true){
          synchronized (p) {
            if(!flags)
              try {
                p.wait();
              } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              };
            p.get();
            flags =false;
            p.notifyAll();
            }
        }
      }
    }).start();
  }
}

生产消费机制一


public class ThreadDemo4 {
  private static boolean flags =false;
  public static void main(String[] args){
    class Goods{
      private String name;
      private int num;
      public synchronized void produce(String name){
        if(flags)
          try {
            wait();
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        this.name =name+"编号:"+num++;
        System.out.println("生产了...."+this.name);
        flags =true;
        notifyAll();
      }
      public synchronized void consume(){
        if(!flags)
          try {
            wait();
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        System.out.println("消费了******"+name);
        flags =false;
        notifyAll();
      }

    }
    final Goods g =new Goods();
    new Thread(new Runnable(){
      public void run(){
        while(true){
          g.produce("商品");
        }
      }
    }).start();
    new Thread(new Runnable(){
      public void run(){
        while(true){
          g.consume();
        }
      }
    }).start();
  }
}

生产消费机制2


public class ThreadDemo4 {
  private static boolean flags =false;
  public static void main(String[] args){
    class Goods{
      private String name;
      private int num;
      public synchronized void produce(String name){
        while(flags)
          try {
            wait();
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        this.name =name+"编号:"+num++;
        System.out.println(Thread.currentThread().getName()+"生产了...."+this.name);
        flags =true;
        notifyAll();
      }
      public synchronized void consume(){
        while(!flags)
          try {
            wait();
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        System.out.println(Thread.currentThread().getName()+"消费了******"+name);
        flags =false;
        notifyAll();
      }

    }
    final Goods g =new Goods();
    new Thread(new Runnable(){
      public void run(){
        while(true){
          g.produce("商品");
        }
      }
    },"生产者一号").start();
    new Thread(new Runnable(){
      public void run(){
        while(true){
          g.produce("商品");
        }
      }
    },"生产者二号").start();
    new Thread(new Runnable(){
      public void run(){
        while(true){
          g.consume();
        }
      }
    },"消费者一号").start();
    new Thread(new Runnable(){
      public void run(){
        while(true){
          g.consume();
        }
      }
    },"消费者二号").start();
  }
}
/*
消费者二号消费了******商品编号:48049
生产者一号生产了....商品编号:48050
消费者一号消费了******商品编号:48050
生产者一号生产了....商品编号:48051
消费者二号消费了******商品编号:48051
生产者二号生产了....商品编号:48052
消费者二号消费了******商品编号:48052
生产者一号生产了....商品编号:48053
消费者一号消费了******商品编号:48053
生产者一号生产了....商品编号:48054
消费者二号消费了******商品编号:48054
生产者二号生产了....商品编号:48055
消费者二号消费了******商品编号:48055
*/

以上是Java中有關多執行緒的使用詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn