如下是简单的线程
for (int i = 0; i <10 ; i++) { new Thread(()->{ System.out.println("1"); },""+i).start(); } System.out.println("2");
2在线程代码后 但不会在线程执行完后才跑
CountDownLatch(减计数器)
CountDownLatch countDownLatch = new CountDownLatch(8);//初始化计数器值 for (int i = 0; i < 8; i++) { new Thread(()->{ System.out.println("1"); countDownLatch.countDown();//数量-1 }).start(); } countDownLatch.await();//等待 计数器归0后往下走 System.out.println("2");
CountDownLatch减计数 计数器不为0休眠等待 归0后唤醒(也是一个线程)
CyclicBarrier(加计数器)
CyclicBarrier cyclicBarrier = new CyclicBarrier(3,()->{ System.out.println("数量达到3"); }); for (int i = 0; i < 3; i++) { int i1=i; new Thread(()->{ System.out.println("第"+i1+"个"); try { cyclicBarrier.await();//等待并+1 } catch (Exception e) { e.printStackTrace(); } }).start(); }
指定个数线程跑完后再执行
Semaphore(限流)(重点)
Semaphore semaphore = new Semaphore(3); for (int i = 0; i < 9; i++) { new Thread(()->{ try { semaphore.acquire();//获取 System.out.println("只能进来指定个数线程"); TimeUnit.SECONDS.sleep(2);//等待2s } catch (InterruptedException e) { e.printStackTrace(); }finally { semaphore.release();//释放 } }).start(); }
同一时间只能跑指定数量的线程