Get the App
SLTechnology News&Howtos  ›  Development  › 

How to introduce the code related to Java multithreaded loop

Shulou Source: shulou.com Published: 2022-06-02 12:40:23 09月26日 Update

This article introduces you how to introduce the code related to Java multithreaded loop, the content is very detailed, interested friends can refer to, hope to be helpful to you.

The Java multithreaded loop requires us to keep learning, and there are many issues that we care about each other all the time. Let's take a look at how to better use this programming language. When each iteration is independent of each other and completing the work of each iteration in the loop body is significant enough to cover the overhead of managing a new task, this sequential loop is suitable for parallelization.

Public voidParallelRecursive (final Executorexec

Listnodes,Collection results) {

For (Node n:nodes) {

Exec.execute (new Runnable () {

Public void run () {

Results.add (n.compute ())

}

});

ParallelRecursive (exec,n.getChildren (), results)

}

}

PublicCollectiongetParallelResults (Listnodes)

Throws InterruptedException {

ExecutorService exec=Executors.newCachedThreadPool ()

Queue resultQueue=newConcurrentLinkedQueue ()

ParallelRecursive (exec,nodes,resultQueue)

Exec.shutdown ()

Exec.awaitTermination (Long.MAX_VALUE,TimeUnit.SECONDS)

Return reslutQueue

}

However, the above procedures cannot deal with situations where there is no solution, and the following procedures can solve this problem.

Public class PuzzleSolverextendsConcurrent

PuzzleSolver {

...

Privatefinal AtomicInteger taskCount=new AtomicInteger (0)

ProtectedRunnable newTask (P pmae M m M J J Noden) {

Return new CountingSolverTask (pdym _ m _ n)

}

ClassCountingSolverTask extends SolverTask {

CountingSolverTask (P pos,Mmove,Node prev) {

Super (pos,move,prev)

TaskCount.incrementAndGet ()

}

Publicvoid run () {

Try {

Super.run ()

}

Finally {

If (taskCount.decrementAndGet () = = 0)

Solution.setValue (null)

}

}

}

}

On how to carry out Java multithreaded loop related code introduction is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Tags: Loops threads code content more programs problems help iterations good important continuous tasks interests guys partners overhead loop body situation meaning Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno macOS Huawei Shulou Technology Apple