一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Java多線程的用法詳細介紹

Java多線程的用法詳細介紹

2020-12-29 15:20qq37267015 Java教程

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

Java多線程的用法詳細介紹

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

1.創建線程

在Java中創建線程有兩種方法:使用Thread類和使用Runnable接口。在使用Runnable接口時需要建立一個Thread實例。因此,無論是通過Thread類還是Runnable接口建立線程,都必須建立Thread類或它的子類的實例。Thread構造函數:

?
1
2
3
4
5
6
7
8
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方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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);
     }
   }
 }

方法二:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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類中和這四種狀態相關的方法。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 開始線程
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方法的定義如下:

?
1
2
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.多線程安全問題

問題原因:當多條語句在操作同一個線程共享數據時,一個線程對多條語句只執行了一部分,還沒執行完,另一個線程參與進來執行,導致共享數據的錯誤。

解決辦法:對多條操作共享數據的語句,只能讓一個線程都執行完,在執行過程中,其他線程不執行。

同步代碼塊:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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--);
      }
    }
  }
}

同步函數

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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

線程間的通信

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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....男
*/

修改上面代碼

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
 張三....男
 張三....男
 張三....男
 張三....男
 */

等待喚醒機制

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
 *線程等待喚醒機制
 *等待和喚醒必須是同一把鎖
 */
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();
  }
}

生產消費機制一

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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 多線程的使用方法,如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

原文鏈接:http://blog.csdn.net/qq_37267015/article/details/77370067

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 日韩精品一区二区三区中文在线 | 视频免费| 99精品在线免费观看 | 99r在线播放| 美女被躁了在线观看视频 | 色帝国亚洲欧美在线蜜汁tv | 久久婷婷五月综合色丁香 | 91制片厂制作果冻传媒123 | 甜蜜调教| 疯狂激吻添下边小说 | 亚洲国产AV无码综合在线 | 99爱在线观看精品视频 | 欧洲vodafonewi精品 | 国产美女在线一区二区三区 | 啾咪成人漫画免费 | 免费黄色小说 | 99精品免费在线观看 | 欧美一级在线全免费 | 99av涩导航 | 校花在公车上被内射好舒 | 成人精品mv视频在线观看 | 日本无遮挡亲吻膜下面免费 | 国产欧美一区二区成人影院 | 国产成人精品一区二区不卡 | 免费观看一级一片 | 国产精品66福利在线观看 | 人禽l交视频在线播放 视频 | sao虎影院桃红视频在线观看 | 扒开黑女人p大荫蒂老女人 扒开大腿狠狠挺进视频 | 日本一区二区三区四区无限 | 国产成人久久久精品一区二区三区 | 日产中文乱码卡一卡二 | 操b图片 | 免费观看视频在线 | 激情婷婷综合久久久久 | 美琪美腿白丝交小说 | 日本人妖网站 | 校花被拖到野外伦小说 | 无遮挡激情| 2020最新韩国理论三级0k | 久青草国产97香蕉在线视频 |