`

多线程 + 同步计数器的连用

阅读更多
public class SimpleWorkThread implements Runnable {
	private String sendMessage;
	private CountDownLatch cdl;

	public SimpleWorkThread(String sendMessage, CountDownLatch cdl) {
		this.sendMessage = sendMessage;
		this.cdl = cdl;
	}

	@Override
	public void run() {
		try {
			System.out.println(sendMessage);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			this.cdl.countDown();
		}
	}

}

 

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class testThread {
	
	public static void main(String[] args)  {

		StringBuilder sendMessage = new StringBuilder();
		sendMessage.append("dsfsdfs") ;
		String sendNumbers = "5" ;
		ExecutorService pool = Executors.newFixedThreadPool(100);
		CountDownLatch cdl = new CountDownLatch(Integer.parseInt(sendNumbers));
		for (int i = 0; i < Integer.parseInt(sendNumbers); i++) {
			pool.execute(new SimpleWorkThread(sendMessage.toString().replace("${money}", i+".00"), cdl));
		}
		try {
			cdl.await();
			System.out.println("hello word!!!");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		pool.shutdown();
	}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics