Demo:
public void testThread() {
List<String> test = new ArrayList<>();
int i = 0;
while (i < 10001) {
i++;
test.add(i + "");
}
//给List加锁,不加会丢数据
List<String> thread = Collections.synchronizedList(test);
//创建线程池
ExecutorService exec = Executors.newFixedThreadPool(3);
thread.forEach(u -> {
exec.execute(() -> {
System.out.println("线程:"+Thread.currentThread().getName());
System.out.println("thread:"+u);
});
});
//任务结束关闭线程池
exec.shutdown();
//判断线程池是否结束,不加会直接结束方法
while (true) {
if (exec.isTerminated()) {
break;
}
}
}
运行结果:
线程:pool-1-thread-2
thread:2
线程:pool-1-thread-2
thread:4
线程:pool-1-thread-2
thread:5
线程:pool-1-thread-1
thread:1
线程:pool-1-thread-2
thread:6
线程:pool-1-thread-3
thread:3
线程:pool-1-thread-2
thread:8
线程:pool-1-thread-1
thread:7
线程:pool-1-thread-2
thread:10
线程:pool-1-thread-3
thread:9
线程:pool-1-thread-2
thread:12
线程:pool-1-thread-1
thread:11
线程:pool-1-thread-2
thread:14
线程:pool-1-thread-3
thread:13
线程:pool-1-thread-2
thread:16
线程:pool-1-thread-1
thread:15
线程:pool-1-thread-2
thread:18
线程:pool-1-thread-3
thread:17
线程:pool-1-thread-2
thread:20
线程:pool-1-thread-1
thread:19
线程:pool-1-thread-2
thread:22
线程:pool-1-thread-3
thread:21
线程:pool-1-thread-2
thread:24
线程:pool-1-thread-1
thread:23
线程:pool-1-thread-2
thread:26
线程:pool-1-thread-3
thread:25
线程:pool-1-thread-2
thread:28
线程:pool-1-thread-1
thread:27
线程:pool-1-thread-2
thread:30
线程:pool-1-thread-3
thread:29
线程:pool-1-thread-2
thread:32
线程:pool-1-thread-1
thread:31
线程:pool-1-thread-2
thread:34
......