我对 Java多线程非常陌生。尝试在 Java 线程中学习 countdownlatch 和 executor 并实现以下代码-
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecutorBasicFramework {
class MyThread extends Thread{
int iCount ; String name;
CountDownLatch latch;
public MyThread(int iCount, String name, CountDownLatch latch) {
super();
this.iCount = iCount;
this.name = name;
this.latch = latch;
}
@Override
public void run() {
for(int i=0;i<10;i++){
System.out.println(name+" Printing .... "+ ++iCount+" L "+latch.getCount());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
latch.countDown();
}
}
public ExecutorBasicFramework() {
createThread();
}
private void createThread() {
ExecutorService exec = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(10);
for(int i=0;i<10;i++){
MyThread thread = new MyThread(i*10, ""+i,latch);
exec.execute(thread);
try {
latch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
exec.shutdownNow();
}
public static void main(String[] args) {
new ExecutorBasicFramework();
}
}
输出如下 -
0 Printing .... 1 L 10
0 Printing .... 2 L 10
0 Printing .... 3 L 10
0 Printing .... 4 L 10
0 Printing .... 5 L 10
0 Printing .... 6 L 10
0 Printing .... 7 L 10
0 Printing .... 8 L 10
0 Printing .... 9 L 10
0 Printing .... 10 L 10
然后流程就像继续等待。我的预期输出与上面类似,但在打印 0 之后,它应该打印 1 到 9 的类似输出,然后程序应该停止。
我认为倒计时正在等待和等待,它不会增加执行器的下一个计数器。所以我无法获得预期的输出。我期待输出像 -
0 Printing .... 1 L 10
0 Printing .... 2 L 10
0 Printing .... 3 L 10
0 Printing .... 4 L 10
0 Printing .... 5 L 10
0 Printing .... 6 L 10
0 Printing .... 7 L 10
0 Printing .... 8 L 10
0 Printing .... 9 L 10
0 Printing .... 10 L 10
1 Printing .... 11 L 9
1 Printing .... 12 L 9
1 Printing .... 13 L 9
1 Printing .... 14 L 9
1 Printing .... 15 L 9
1 Printing .... 16 L 9
1 Printing .... 17 L 9
1 Printing .... 18 L 9
1 Printing .... 19 L 9
1 Printing .... 20 L 9
and So on ...
2 Printing .... 21 L 8
2 Printing .... 22 L 8
2 Printing .... 23 L 8
对于锁存器的每个递减计数器,下一个线程池必须执行计数直到 10。然后它必须再次减少锁存器计数器,并且该过程再次重复,直到线程 9 完成相同
请提出一些意见。