import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 多线程
*
* @author 你哥
* <p>
* 2999年1月1日
*/
public class CountDownLatchTest {
/**
* – the number of threads in the pool
*/
private static final int THREAD_NUM = 5;
/**
* 实现多线程的基本方法之一
*/
class SubRunner implements Runnable {
// task 可以是你的类
String task;
CountDownLatch latch;
public SubRunner(String task, CountDownLatch latch) {
this.task = task;
this.latch = latch;
}
@Override
public void run() {
try {
// 获取正在执行任务的线程
Thread thread = Thread.currentThread();
// 获取线程的名称
String threadName = thread.getName();
// 这里处理你的业务
System.out.println(task + "," + threadName + ",start");
Thread.sleep(5000);
System.out.println(task + "," + threadName + ",end");
} catch (InterruptedException e) {
System.out.println("error-" + task);
throw new RuntimeException(e);
} finally {
// countDown一定要执行
latch.countDown();
}
}
}
/**
* 实现多线程打印出一个数组
*/
private void printArrays() {
List<String> tasks = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8");
CountDownLatch latch = new CountDownLatch(tasks.size());
// 开始
ExecutorService pool = Executors.newFixedThreadPool(THREAD_NUM);
for (String task : tasks) {
pool.execute(new SubRunner(task, latch));
}
pool.shutdown();
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
CountDownLatchTest t = new CountDownLatchTest();
t.printArrays();
}
}
实用的多线程
最新推荐文章于 2024-09-12 23:58:52 发布