[精讚] [會員登入]
938

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

你可能感興趣的文章

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

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

使用poi 解析 docx 原先是想解析出在docx 中的文字跟圖片, 但是, 有些我們認為是圖片, 其實是用方程式表示, 實在是太麻煩了 就記錄一

Spring Boot Maven wrappers maven, mvnw, build command

ArrayList 想移除特定值 想移出water, 使用lambda 的方式如下 List<String> fruits = new Arr

spring boot jpa 使用多個欄位排序 我有一entity 叫 team 資料欄下如下 @Id @GeneratedValue(strategy = Gener

隨機好文

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

java.time 時間 instant java.time

windows ad 如何得知 dn 值 如何得知 windows ad 上的使用者dn 值 https://support.symantec.com/en_US

臺中市雲端校務系統與Windows AD帳號整合(8) 三 開機啟動服務 3-1 Windows Server上隨系統開機啟動服務 寫一個bat檔 cd C:UsersAdmi

[web] 自訂模組-打字機與跑馬燈效果 自訂模組-打字機效果