[精讚] [會員登入]
467

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

你可能感興趣的文章

java.time 時間 instant java.time

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

Thread java thread

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

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

java lambda files filter java, files filter, lambda

我有話要說

>>

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

訪客留言

[無留言]

隨機好文

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

download a file from spring boot controllers ownload a file from spring boot controllers

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

apache 反向代理 80轉443轉8080 apache, proxy pass

臺中市校務雲端系統與Windows AD帳號整合(1) active directory,ldaps,雲端校務系統