[精讚] [會員登入]
160

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

你可能感興趣的文章

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

ArrayList 與 HashMap 範例 public static void main(String[] args) { String titleIds = &

java lambda files filter java, files filter, lambda

刪除資料夾內的檔案 lambda 一行文 Arrays.stream(new File("/folder/path").

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

Thread java thread

我有話要說

>>

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

訪客留言

[無留言]

隨機好文

java-身份証字號驗証 FormatCheck.java public class FormatCheck { private volatile

00-F2 的 IPV6 反解設定 近日, 強者我的大神同事, line 傳來一句: igogo 上次你那個ipv6的設定檔 再幫我跑一次 如連結 程式都寫

[scratch2] 分數排名 在清單中隨机產生5名學生的考試分數, 再利用另一個清單排名 想法, 分數愈高者排名愈好, 例如名次是第5名, 那分數是最

在docker裡跑spring boot+mongo(二) 使用docker-compose 管理多個container 前篇使用docker run 一次建一個container

將google試算表當作簡易資料庫,利用Google apps cript 在網頁上操作查詢 將google試算表當作簡易資料庫,利用apps cript 在網頁上操作查詢 若我有一試算表資料 縣市 status