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