Requires that the main thread executes after the child thread executes.
This is easy to handle, the child threads are set to not be daemon threads
Then process 4 child threads
We can make each thread direct as follows
static class MyThread {
public static void start(int begin, int step){
Thread t = new Thread(()->{
int localSum = 0;
for (int i = begin;i<=100;i+=step){
localSum+=i;
}
});
t.setDaemon(false);
t.start();
}
}
}
Create a blocking queue to store the results of each task block
private static final LinkedBlockingQueue<Integer> queue =
new LinkedBlockingQueue<>(10);
Put the execution result of the child thread into the blocking queue
queue.offer(localSum);
Accumulate the results using the atomic class of the concurrent package
private static final AtomicInteger sum = new AtomicInteger(0);
public static void test3()throws InterruptedException{
int sum = 0;
Lock lock = new ReentrantLock();
AtomicInteger count = new AtomicInteger(0);
for(int i = 0 ; ;i++){
MyThread.start(i,4);
count.getAndIncrement();
if(i==4){
break;
}
}
while(count.decrementAndGet()>0){
Integer integer = null;
while(queue.size()<=0){
Thread.sleep(0);
}
lock.lock();
integer = queue.take();
lock.unlock();
sum+=Integer.valueOf(integer);
}
System.out.println(sum);
}
This will solve the problem
full code