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();
}
}
}