[精讚] [會員登入]
903

Thread

java thread

分享此文連結 //n.sfs.tw/15583

分享連結 Thread@igogo
(文章歡迎轉載,務必尊重版權註明連結來源)
2023-03-08 13:27:10 最後編修
2022-01-13 23:45:26 By igogo
 

 

 

thread 使用lambda

List<String> names = new ArrayList<>();

        names.add("1mary");
        names.add("2jane");
        names.add("3tina");

        names.forEach(name -> {
            Runnable r = () -> {
                int i = 0;
                try {
                    while (i < 5) {
                        Thread.sleep((int) (Math.random() * 3000));
                        System.out.println("------" + " stage " + i + "," + name + " is running");
                        i++;
                    }

                    System.out.println(name + " has finished");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            };

            Thread thread = new Thread(r);
            thread.start();
        });

 

如果我想等所有的執行緒跑完, 回到主程式

 

則要加上thread.join()

		List<String> names = new ArrayList<>();

		names.add("1mary");
		names.add("2jane");
		names.add("3tina");

		names.forEach(name -> {
			Runnable r = () -> {
				int i = 0;
				try {
					while (i < 5) {
						Thread.sleep((int) (Math.random() * 3000));
						System.out.println("------" + " stage " + i + "," + name + " is running");
						i++;
					}

					System.out.println(name + " has finished");

				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			};

			Thread thread = new Thread(r);
			thread.start();
			try {
				thread.join();
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
		});

 

https://www.baeldung.com/java-thread-join

 

END

你可能感興趣的文章

利用maven建立一個可執行的jar檔 利用maven建立一個可執行的jar檔

讀取特定資料夾下的xls檔 讀取特定資料夾下的xls檔

[vue.js] 設定 content type 今天在wickt 端怎麼就是收不到vue.js 以post 傳過來的資料 找了好久才發現 application/jso

停止多執行緒 利用主程式呼叫多執行緒時, 要怎麼停止正在執行的多執行緒

spring boot 使用jdbc連接mariadb spring boot, mariadb, jdbc, rowmapper

Spring Boot Maven wrappers maven, mvnw, build command

我有話要說

>>

限制:留言最高字數1000字。 限制:未登入訪客,每則留言間隔需超過10分鐘,每日最多5則留言。

訪客留言

[無留言]

隨機好文

[vue.js] 設定 content type 今天在wickt 端怎麼就是收不到vue.js 以post 傳過來的資料 找了好久才發現 application/jso

[vue.js] input event Form-Input-Components-using-Custom-Events

vue.js modal 作兩個選項按鈕並導向不同頁面 vue.js modal 作兩個選項按鈕

vue.js component 在parent與child 傳值 component 在parent與child 傳值

axios vuejs application/x-www-form-urlencoded 送資料 VUE.JS 以 application/x-www-form-urlencoded 送資料