使用CountDownLatch启动和停止线程

package File;

import java.util.concurrent.CountDownLatch;


public class Indexer {
	Indexer(){};
	public long timeTasks(int nThreads,final Runnable stak) throws InterruptedException{
		final CountDownLatch startGate=new CountDownLatch(1);
		final CountDownLatch endGate=new CountDownLatch(nThreads);
		for(int i=0;i<nThreads;i++){
			Thread thread=new Thread(){
				public void run() {
					try {
						startGate.await();//  使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断。 关门
						try {
							stak.run();
						} finally {
							endGate.countDown();
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
			thread.start();
		}
		long start=System.nanoTime();
		startGate.countDown();//递减锁存器的计数,如果计数到达零,则释放所有等待的线程。 开门
		endGate.await();
		long end=System.nanoTime();
		return end-start;
		
	}

	
	public static void main(String[] args) throws InterruptedException {
		System.out.println(new Indexer().timeTasks(10, new Runnable() {
			
			@Override
			public void run() {
				System.out.println(1);
				
			}
		}));
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用CountDownLatch配合Future和Callable实现返回子线程的结果。以下是示例代码: ```java import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ThreadDemo { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executorService = Executors.newCachedThreadPool(); CountDownLatch latch = new CountDownLatch(1); Future<Integer> future = executorService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { int result = 0; // 执行一些耗时的操作 for (int i = 0; i < 1000000; i++) { result += i; } return result; } }); new Thread(() -> { try { latch.await(); System.out.println("子线程返回结果:" + future.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } }).start(); // 唤醒等待的子线程 latch.countDown(); executorService.shutdown(); } } ``` 在上面的代码中,我们创建了一个CountDownLatch对象,然后在主线程启动了一个子线程,子线程执行了一些耗时的操作,返回了结果。在主线程中,我们使用Future对象获取了子线程的返回结果,并且在启动了一个新的线程来处理这个返回结果。在新线程中,我们使用CountDownLatch的await()方法等待主线程调用countDown()方法唤醒它,然后再通过Future的get()方法获取子线程的返回结果。最后,我们调用ExecutorService的shutdown()方法关闭线程池。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值