您的位置:首页 > 其它

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

2012-05-31 21:57 459 查看
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();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐