Vea el video del proceso de aprendizaje: [Crazy God Says Java]
https://www.bilibili.com/video/BV1B7411L7tE?p=13
Bienvenidos a todos para apoyar ¡Oh, muy concienzudo maestro!
Tres métodos, ejemplos de código
1 、 newSingleThreadExecutor
package com.add;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by zjl
* 2020/11/25
**/
public class ExecutorsTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor(); //单个线程
// ExecutorService executorService = Executors.newFixedThreadPool(5); //固定大小的线程池
// ExecutorService executorService = Executors.newCachedThreadPool(); //可伸缩的,遇强则强,遇弱则弱
try {
for (int i = 0; i < 10; i++) {
// 使用了线程池之后,使用线程池来创建线程
executorService.execute(()->{
System.out.println(Thread.currentThread().getName() + "is ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 线程池用完,程序结束,关闭线程池
executorService.shutdown();
}
}
}
resultado de la operación:
pool-1-thread-1is ok
pool-1-thread-1is ok
pool-1-thread-1is ok
pool-1-thread-1is ok
pool-1-thread-1is ok
pool-1-thread-1is ok
pool-1-thread-1is ok
pool-1-thread-1is ok
pool-1-thread-1is ok
pool-1-thread-1is ok
Process finished with exit code 0
2 、 newFixedThreadPool
package com.add;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by zjl
* 2020/11/25
**/
public class ExecutorsTest {
public static void main(String[] args) {
// ExecutorService executorService = Executors.newSingleThreadExecutor(); //单个线程
ExecutorService executorService = Executors.newFixedThreadPool(5); //固定大小的线程池
// ExecutorService executorService = Executors.newCachedThreadPool(); //可伸缩的,遇强则强,遇弱则弱
try {
for (int i = 0; i < 10; i++) {
// 使用了线程池之后,使用线程池来创建线程
executorService.execute(()->{
System.out.println(Thread.currentThread().getName() + "======》is ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 线程池用完,程序结束,关闭线程池
executorService.shutdown();
}
}
}
Resultado de la operación:
Podemos ver que puede haber hasta 5 subprocesos ejecutándose juntos.
3. newCachedThreadPool
package com.add;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by zjl
* 2020/11/25
**/
public class ExecutorsTest {
public static void main(String[] args) {
// ExecutorService executorService = Executors.newSingleThreadExecutor(); //单个线程
// ExecutorService executorService = Executors.newFixedThreadPool(5); //固定大小的线程池
ExecutorService executorService = Executors.newCachedThreadPool(); //可伸缩的,遇强则强,遇弱则弱
try {
for (int i = 0; i < 10; i++) {
// 使用了线程池之后,使用线程池来创建线程
executorService.execute(()->{
System.out.println(Thread.currentThread().getName() + "======》is ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 线程池用完,程序结束,关闭线程池
executorService.shutdown();
}
}
}
Resultado de la ejecución: como
podemos ver, el grupo de subprocesos cambiará automáticamente su tamaño.