java for循环改造多线程例子
 1 package com.company;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 import java.util.concurrent.CountDownLatch;
 6 import java.util.concurrent.ExecutorService;
 7 import java.util.concurrent.Executors;
 8 
 9 public class Main {
10 
11     public static void main(String[] args) {
12         // write your code here
13         System.out.println("Hello World");
14         int TOTAL_THREADS = 4;//线程数
15         //数据库中的100条数据;
16         List list = new ArrayList();
17         for (int i = 0; i < 100; i++) {
18             list.add(i);
19         }
20         //Executors创建线程池new固定的10个线程
21         ExecutorService taskExecutor = Executors.newCachedThreadPool();
22         final CountDownLatch latch = new CountDownLatch(list.size());//用于判断所有的线程是否结束
23         System.out.println("个数==" + list.size());
24 
25         for (int m = 0; m < list.size(); m++) {
26             final int n = m;//内部类里m不能直接用,所以赋值给n
27             Runnable run = new Runnable() {
28                 public void run() {
29                     try {
30                         System.out.println("我在执行=" + n);
31                     } finally {
32                         latch.countDown(); //每次调用CountDown(),计数减1
33                     }
34                 }
35             };
36             taskExecutor.execute(run);//开启线程执行池中的任务。还有一个方法submit也可以做到,它的功能是提交指定的任务去执行并且返回Future对象,即执行的结果
37         }
38 
39         try {
40             //等待所有线程执行完毕
41             latch.await();//主程序执行到await()函数会阻塞等待线程的执行,直到计数为0
42         } catch (InterruptedException e) {
43             e.printStackTrace();
44         }
45         taskExecutor.shutdown();//关闭线程池
46         //所有线程执行完毕,执行主线程
47     }
48 
49 }

 

posted on 2023-01-14 15:52  武定路  阅读(581)  评论(0编辑  收藏  举报