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

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

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

服務器之家 - 編程語言 - Java教程 - Java多線程基礎

Java多線程基礎

2022-03-03 00:38冬日毛毛雨 Java教程

這篇文章主要介紹Java多線程基礎,線程是進程的一個實體,是CPU調度和分派的基本單位,它是比進程更小的能獨立運行的基本單位,多線程指在單個程序中可以同時運行多個不同的線程執行不同的任務,下面來學習具體的詳細內容

一、線程

什么是線程:

線程是進程的一個實體,是CPU調度和分派的基本單位,它是比進程更小的能獨立運行的基本單位。

什么是多線程:

多線程指在單個程序中可以同時運行多個不同的線程執行不同的任務。

二、創建多線程的方式

多線程的創建方式有三種:ThreadRunnableCallable

1、繼承Thread類實現多線程

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Thread thread = new Thread() {
      @Override
      public void run() {
          super.run();
          while (true) {
              try {
                  Thread.sleep(500);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
              System.out.println("1:" + Thread.currentThread().getName());
              System.out.println("2:" + this.getName());
          }
      }
  };
  thread.start();

2、實現Runnable接口方式實現多線程

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("3:" + Thread.currentThread().getName());
                }
            }
        });
        thread1.start();

3、Callable接口創建線程

?
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 CallableTest {
 
    public static void main(String[] args) {
        System.out.println("當前線程是:" + Thread.currentThread());
        Callable myCallable = new Callable() {
            @Override
            public Integer call() throws Exception {
                int i = 0;
                for (; i < 10; i++) {
 
                }
                //當前線程
                System.out.println("當前線程是:" + Thread.currentThread()
                        + ":" + i);
                return i;
            }
        };
        FutureTask<Integer> fu = new FutureTask<Integer>(myCallable);
        Thread th = new Thread(fu, "callable thread");
 
        th.start();
 
        //得到返回值
        try {
            System.out.println("返回值是:" + fu.get());
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

當前線程是:Thread[main,5,main]
當前線程是:Thread[callable thread,5,main]:10
返回值是:10

總結:

實現Runnable接口相比繼承Thread類有如下優勢:

  • 可以避免由于Java的單繼承特性而帶來的局限;
  • 增強程序的健壯性,代碼能夠被多個線程共享,代碼與數據是獨立的;
  • 適合多個相同程序代碼的線程區處理同一資源的情況。

實現Runnable接口和實現Callable接口的區別:

  • Runnable是自從java1.1就有了,而Callable是1.5之后才加上去的
  • Callable規定的方法是call() , Runnable規定的方法是run()
  • Callable的任務執行后可返回值,而Runnable的任務是不能返回值是(void)
  • call方法可以拋出異常,run方法不可以
  • 運行Callable任務可以拿到一個Future對象,表示異步計算的結果。它提供了檢查計算是否完成的方法,以等待計算的完成,并檢索計算的結果。通過Future對象可以了解任務執行情況,可取消任務的執行,還可獲取執行結果。
  • 加入線程池運行,Runnable使用ExecutorServiceexecute方法,Callable使用submit方法。

三、線程的生命周期與狀態

Java多線程基礎

四、線程的執行順序

Join線程的運行順序

原理:

1、定時器

?
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
import java.util.Timer;
import java.util.TimerTask;
 
public class TraditionalTimerTest {
    public static void main(String[] args) {
 
//         new Timer().schedule(new TimerTask() {
//             @Override
//             public void run() {
//
//                 System.out.println("bombing!");
//             }
//         },10000);
 
        class MyTimberTask extends TimerTask {
            @Override
            public void run() {
 
                System.out.println("bombing!");
                new Timer().schedule(new MyTimberTask(), 2000);
            }
        }
 
 
        new Timer().schedule(new MyTimberTask(), 2000);
 
 
        int count = 0;
        while (true) {
            System.out.println(count++);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
 
        }
    }
}

0
1
bombing!
2
3
bombing!
4
5
bombing!
6
省略...

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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
public class TraditionalThreadSynchronized {
 
    public static void main(String[] args) {
 
        new TraditionalThreadSynchronized().init();
    }
 
    private void init() {
        final Outputer outputer = new Outputer();
 
        new Thread(new Runnable() {
            @Override
            public void run() {
 
                while (true) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    outputer.output("kpioneer");
 
                }
            }
        }).start();
 
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//
//                while (true) {
//                    try {
//                        Thread.sleep(10);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    outputer.output2("Tom");
//
//                }
//            }
//        }).start();
 
        new Thread(new Runnable() {
            @Override
            public void run() {
 
                while (true) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    outputer.output3("Jack");
 
                }
            }
        }).start();
    }
 
  static   class Outputer {
 
        public void output(String name) {
 
            int len = name.length();
 
            synchronized (Outputer.class) {
 
                for (int i = 0; i < len; i++) {
                    System.out.print(name.charAt(i));
                }
                System.out.println();
            }
 
        }
 
        public synchronized void output2(String name) {
            int len = name.length();
 
            for (int i = 0; i < len; i++) {
                System.out.print(name.charAt(i));
            }
            System.out.println();
        }
 
      public static synchronized void output3(String name) {
          int len = name.length();
 
          for (int i = 0; i < len; i++) {
              System.out.print(name.charAt(i));
          }
          System.out.println();
      }
    }
}

3、線程同步通信技術

子線程循環10次,接著主線程循環100,接著又回到子線程循環10次,接著再回到主線程有循環100,如此循環50次,請寫出程序。

?
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
public class TraditionalThreadCommunication {
    public static void main(String[] args) {
 
        final Business business = new Business();
        new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 1; i <= 50; i++) {
                            business.sub(i);
                        }
                    }
                }
        ).start();
        for (int i = 1; i <= 50; i++) {
            business.main(i);
        }
    }
 
}
 
/**
 *要用到共同數據(包括同步鎖)的若干方法應該歸在同一個類身上,
 * 這種設計正好體現了高類聚和和程序的健壯性
 */
class Business {
    private boolean bShouldSub = true;
    public synchronized void sub(int i) {
        if(!bShouldSub) {
 
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for (int j = 1; j <= 10; j++) {
            System.out.println("sub thread sequece of " + j + ",loop of " + i);
 
        }
        bShouldSub = false;
        this.notify();
    }
 
    public synchronized void main(int i) {
        if(bShouldSub) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for (int j = 1; j <=100; j++) {
            System.out.println("main thread sequece of " + j + ",loop of " + i);
 
        }
        bShouldSub = true;
        this.notify();
    }
}

sub thread sequece of 1,loop of 1
sub thread sequece of 2,loop of 1
sub thread sequece of 3,loop of 1
sub thread sequece of 4,loop of 1
sub thread sequece of 5,loop of 1
sub thread sequece of 6,loop of 1
sub thread sequece of 7,loop of 1
sub thread sequece of 8,loop of 1
sub thread sequece of 9,loop of 1
sub thread sequece of 10,loop of 1
main thread sequece of 1,loop of 1
main thread sequece of 2,loop of 1
main thread sequece of 3,loop of 1
main thread sequece of 4,loop of 1
main thread sequece of 5,loop of 1
main thread sequece of 6,loop of 1
main thread sequece of 7,loop of 1
main thread sequece of 8,loop of 1
main thread sequece of 9,loop of 1
main thread sequece of 10,loop of 1
main thread sequece of 11,loop of 1
省略中間...
main thread sequece of 99,loop of 1
main thread sequece of 100,loop of 1
sub thread sequece of 1,loop of 2
sub thread sequece of 2,loop of 2
sub thread sequece of 3,loop of 2
sub thread sequece of 4,loop of 2
sub thread sequece of 5,loop of 2
sub thread sequece of 6,loop of 2
sub thread sequece of 7,loop of 2
sub thread sequece of 8,loop of 2
sub thread sequece of 9,loop of 2
sub thread sequece of 10,loop of 2
main thread sequece of 1,loop of 2
main thread sequece of 2,loop of 2
main thread sequece of 3,loop of 2
省略...

到此這篇關于Java多線程基礎的文章就介紹到這了,更多相關Java多線程內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!

原文鏈接:https://juejin.cn/post/7016565183694766088

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 日韩精品国产自在欧美 | 韩国三级日本三级香港三级黄 | 91九色porn偷拍在线 | 免费在线观看视频 | 欧美亚洲第一区 | 911精品国产亚洲日本美国韩国 | 四虎影视紧急入口地址大全 | 免费午夜影片在线观看影院 | 福利一区在线观看 | 国产精品日本亚洲777 | 亚洲高清国产拍精品动图 | 成人青青草 | 艾秋果冻麻豆老狼 | 小sao货水好多真紧h的视频 | 极品美女aⅴ高清在线观看 极品ts赵恩静和直男激战啪啪 | 2021最新国产成人精品免费 | 欧美成黑人性猛交xxoo | 国产高清经典露脸3p | 四虎永久网址影院 | 精品国产品香蕉在线观看75 | 日本道三区播放区 | 女明星放荡高h日常生活 | 亚洲高清影院 | 午夜DV内射一区区 | 日本高清在线观看天码888 | 小小水蜜桃免费影院 | 双性np玩烂了np欲之国的太子 | 亚洲高清视频在线观看 | 青青青久在线视频免费观看 | 狠狠综合久久综合网站 | 国产婷婷成人久久av免费高清 | 欧美日韩中文字幕一区二区高清 | 蜜桃影像传媒破解版 | 精品国产自在在线在线观看 | 亚洲国产成人精品不卡青青草原 | 男男羞羞视频网站国产 | 天天操天天干天天做 | chinaese中国女人厕所小便 | 欧美洲大黑香蕉在线视频 | 久久伊人在| 女攻双性 |