import com.alibaba.fastjson.JSON; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; public class Test2 { public static void main(String[] args) { System.out.println("开始多线程同步聚餐事情:"); long startTime = System.currentTimeMillis();
Hashtable map = new Hashtable(); try { List<Thread> threadList = new ArrayList<>(); threadList.add(new Thread(() -> { System.out.println("京东买厨具"); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } map.put("买厨具", "京东买厨具---->OK"); })); threadList.add(new Thread(() -> { System.out.println("叮咚买菜"); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } map.put("买菜", "叮咚买菜---->OK"); })); threadList.add(new Thread(() -> { System.out.println("世纪联华商店买点肉"); try { Thread.sleep(8000); } catch (InterruptedException e) { e.printStackTrace(); } map.put("买点肉", "世纪联华商店买点肉---->OK"); })); threadList.add(new Thread(() -> { System.out.println("金谊广场买点小酒"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } map.put("买点小酒", "金谊广场买点小酒---->OK"); })); threadList.add(new Thread(() -> { System.out.println("呼叫 张三快来喝酒"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } map.put("呼叫 张三", "张三到达现场---->OK"); })); threadList.add(new Thread(() -> { System.out.println("呼叫 李四快来喝酒"); try { Thread.sleep(7000); } catch (InterruptedException e) { e.printStackTrace(); } map.put("呼叫 李四", "李四到达现场---->OK"); })); if (threadList.size() > 0) { for (Thread t : threadList) { t.start(); } for (Thread t : threadList) { t.join(); } } } catch (Exception e) { System.out.println("开始聚餐出现异常"); } System.out.println("总共用时" + (System.currentTimeMillis() - startTime) + "ms"); System.out.println("开始聚餐:" + JSON.toJSONString(map)); } }