[精讚] [會員登入]
1277

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

你可能感興趣的文章

Arrays.asList 後想再add出現 UnsupportedOperationException 這個問題真是搞死我了 List<String> fruits = Arrays.asList("a

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

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

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

keycloak 透過java client lib新增user 使用keycloak-admin-client lib maven <dependency> <gro

java.time 時間 instant java.time

隨機好文

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

java.time 時間 instant java.time

proxmox lxc 救援 今天突然接到一名強者我朋友的臨時求援 他說他把pve 從5.1升到5.2後, kvm的虛擬机器都沒問題 , 但是lxc的

臺中市雲端校務系統與Windows AD帳號整合(3) LDAP的基本概念

雲端校務系統與OPENLDAP帳號整合(3) 二 建置更改密碼服務 下載校端更改密碼程式: 連結 檢查是否安裝java 8 #java -version 安裝open