Runnable 示例代码
CountDownLatch 示例代码
package com.doggy.doggy;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @desc 多线程示例
* @author ashly
* @date 2020/1/15 9:55
**/
@Slf4j
public class ThreadExample {
//创建2个线程用于处理任务
private static final ExecutorService executor = Executors.newFixedThreadPool(2);
public static void main(String[] args){
int count = 10;
//任务计数
CountDownLatch latch = new CountDownLatch(count);
System.out.println("提交任务");
for (int i = 0; i < count; i++) {
executor.submit(new DemoRunnable(i, latch));
}
//任务等待
try {
latch.await();//等待,当计数latch减到0时,所有线程并行执行
} catch (InterruptedException e) {
log.info("Thread Interrupted!");
Thread.currentThread().interrupt();
}
System.out.println("执行完毕");
}
}
class DemoRunnable implements Runnable {
int anInt;
CountDownLatch latch;
DemoRunnable(int anInt, CountDownLatch latch){
this.anInt = anInt;
this.latch = latch;
}
@Override
public void run() {
if (anInt == 3 || anInt == 5 || anInt == 9){//模拟不同任务的处理时间不同
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("执行完第" + (anInt + 1) + "个任务,latch's count: " + latch.getCount() );
latch.countDown();
}
}
运行结果
提交任务
执行完第1个任务,latch’s count: 10
执行完第3个任务,latch’s count: 9
执行完第2个任务,latch’s count: 8
执行完第5个任务,latch’s count: 7
执行完第6个任务,latch’s count: 6
执行完第4个任务,latch’s count: 6
执行完第7个任务,latch’s count: 5
执行完第8个任务,latch’s count: 4
执行完第9个任务,latch’s count: 3
执行完第10个任务,latch’s count: 1
执行完毕