CountDownLatch 控制多线程 让多个线程执行完后再依次做其他的

来源:互联网 发布:oracle数据库创建索引 编辑:程序博客网 时间:2024/05/21 12:46

package com.ps;

import java.util.concurrent.CountDownLatch;

public class TestRunnable implements Runnable{
 private int tickets = 100;
 String s = new String("  ");
 CountDownLatch cdl = new CountDownLatch(10);//这里的10和下面要启动的线程数必须一样
 @Override
 public void run() {
  // TODO Auto-generated method stub
  while(tickets>0){
   synchronized(s){
    if(tickets>0){
     try {
      Thread.sleep(100);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
     System.out.println(Thread.currentThread().getName() +"is saling tickets  "+tickets--);
    }
   }
  }
  cdl.countDown();
 }
 
 public static void main(String[] args){
  
  TestRunnable testRunnable = new TestRunnable();
  for(int i=0;i<10;i++){
   new Thread(testRunnable).start();
  }
  try {
   System.out.println(testRunnable.cdl.getCount());
   testRunnable.cdl.await();//如果不用countdownlatch的await控制,下面的操作会和多线程并行
   System.out.println("等十个线程完后再做做其他的");
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

原创粉丝点击