Table of contents
1. Java uses multi-threading to speed up loop efficiency (recommended the third type!!!)
The first type: thread pool combination lock
The second type: paging concept execution thread
The third type: Advanced version of the paging concept execution thread! ! ! !
1. Java uses multithreading to speed up loop efficiency (Recommended No. 3! ! ! !)
The first type: thread pool combination lock
Involved knowledge: Executors (thread pool), CountDownLatch (locking)
Advantages: The code is concise, easy to read, and stable performance;
Disadvantages: The thread pool created by Executors is common. If multiple places use this method of looping multi-threading, it will seize the thread pool resources, which will also reduce the running speed;
import .*;
import ;
import ;
import ;
public class test{
public static void main(String[] args) throws Exception {
/**
* Two key points:
* 1. Use Executors to implement a fixed-size thread pool to achieve the purpose of controlling hardware resource consumption.
* 2. Use CountDownLatch to ensure that all the multiple threads in the loop are executed, and then execute the subsequent code.
*/
// Fixed thread pool (current thread pool size is 5
final ExecutorService executor = (5);
// Initialize the data
List<Map<String,Object>> list = new ArrayList<>();
for(int i=0;i<50;i++){
Map<String,Object> object = new HashMap<>();
("index",i);
(object);
}
// Initialize the timer
final CountDownLatch cdl = new CountDownLatch(());
("======= Thread start =======");
//Travel
for(final Map<String,Object> object:list){
// Turn on thread
(new Runnable() {
@Override
public void run() {
try {
Thread t = ();
String name = ();
// Simulation operation time-consuming
(500);
(name+": execute to "+("index"));
("status","executed");
} catch (InterruptedException e) {
();
}
// Lock-1
();
}
});
}
// Call the locked await() method, the thread will be suspended, it will wait until the count value is 0 before continuing to execute
// This way we can ensure that the following code has been left after all the above threads have been executed
();
//Close the thread pool
();
("======= End of thread =======");
// Verify the correctness of multithreading
for(Map<String,Object> object:list){
(("index") + ":" + ("status"));
}
}
}
The second type: paging concept execution thread
Knowledge involved: CountDownLatch (locked)
Advantages: fast running speed;
Disadvantages: It is difficult to read code;
public static void main(String[] args) throws InterruptedException {
/**
* Two key points:
* 1. Set the number of threads, use the concept of paging, split the collection into several components and execute threads in batches.
* 2. Use CountDownLatch to ensure that all the multiple threads in the loop are executed, and then execute the subsequent code.
*/
// Initialize the data
final List<Map<String,Object>> list = new ArrayList<>();
for(int i=0;i<6;i++){
Map<String,Object> object = new HashMap<>();
("index",i);
(object);
}
int size = (); //Total number of sets
int theadCount = 5; // Number of execution threads
int splitCount = size / theadCount + (size % theadCount != 0 ? 1 : 0); //Calculate the number of splits and round up
final CountDownLatch cdl = new CountDownLatch(size); //Counter
for (int i = 1; i <= theadCount; i++) {
final int beign = (i - 1) * splitCount;
final int end = (i * splitCount) > size ? size : i * splitCount;
if(beign >= end) break;
new Thread(new Runnable() {
@Override
public void run() {
for (int j = beign; j < end; j++) {
try {
Thread t = ();
String name = ();
// Simulation operation time-consuming
(500);
Map<String, Object> object = (j);
(name+": execute to "+("index"));
("status","executed");
} catch (InterruptedException e) {
();
}
// Lock-1
();
}
}
}).start();
}
// Call the locked await() method, the thread will be suspended, it will wait until the count value is 0 before continuing to execute
// This way we can ensure that the following code has been left after all the above threads have been executed
();
("======= End of thread =======");
// Verify the correctness of multithreading
for(Map<String,Object> object:list){
(("index") + ":" + ("status"));
}
}
The third type: Advanced version of the paging concept execution thread! ! ! !
Involved knowledge: CountDownLatch (lock), object encapsulation;
Advantages: fast running speed, simple and elegant code;
shortcoming:;
package ;
import ;
import ;
import ;
import ;
import ;
import ;
/***
* Multi-threaded optimization by lyx 20230318
* Run multiple threads in a loop to improve execution speed
*/
public class TheadMultis {
private Integer theadCount; //Number of threads
private Integer size; // collection size
private Integer timeOut = 60; //Timeout time (unit: minutes)
private Function function; //Execution method
public interface Function {
void run(int i);
}
public TheadMultis(int theadCount, int size, Function function) {
= theadCount;
= size;
= function;
}
public TheadMultis(int theadCount, int timeOut, int size, Function function) {
= theadCount;
= timeOut;
= size;
= function;
}
public void start() throws InterruptedException,TheadMultisException {
int size = ; //Total number of sets
int theadCount = ; // Number of execution threads
int splitCount = size / theadCount + (size % theadCount != 0 ? 1 : 0); //Calculate the number of splits and round up
final CountDownLatch cdl = new CountDownLatch(size); //Counter
for (int i = 1; i <= theadCount; i++) {
final int beign = (i - 1) * splitCount;
final int end = (i * splitCount) > size ? size : i * splitCount;
if(beign >= end) break;
new Thread(new Runnable() {
@Override
public void run() {
for (int j = beign; j < end; j++) {
try{
(j);
}catch (Exception e){
();
}
// Lock-1
();
}
}
}).start();
}
int time = != null ? : 60;
// Call the locked await() method, the thread will be suspended, it will wait until the count value is 0 before continuing to execute
// This way we can ensure that the following code has been left after all the above threads have been executed
try{
if(!(time, )){
throw new TheadMultisException("Execute for more than "+ time +" minutes");
}
}catch (InterruptedException e){
throw e;
}
}
public class TheadMultisException extends Exception{
public TheadMultisException() {
super();
}
public TheadMultisException(String s) {
super(s);
}
}
public static void main(String[] args) throws Exception {
// Initialize the data
final List<Map<String,Object>> list = new ArrayList<>();
for(int i=0;i<10;i++){
Map<String,Object> object = new HashMap<>();
("index",i);
(object);
}
new TheadMultis(2, 1,(), new () {
@Override
public void run(int i) {
Thread t = ();
String name = ();
// Simulation operation time-consuming
try {
// (1000 * 60);
(500);
} catch (InterruptedException e) {
();
}
Map<String, Object> object = (i);
(name+": execute to "+("index"));
("status","executed");
}
}).start();
("======= End of thread =======");
// Verify the correctness of multithreading
for(Map<String,Object> object:list){
(("index") + ":" + ("status"));
}
}
}