Executors.newSingleThreadExecutor();创建单个线程
Executors.newFixedThreadPool(5);创建固定的线程池大小
Executors.newCachedThreadPool();创建可伸缩的线程,根据cpu开启线程
1.Executors.newSingleThreadExecutor();创建单个线程
package pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Demo01 {
public static void main(String[] args) {
ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
try {
for (int i = 0; i <10 ; i++) {
threadExecutor.execute(()->{
System.out.println(Thread.currentThread().getName());
});
}
} catch (Exception e) {
e.printStackTrace();
}finally {
threadExecutor.shutdown();
}
}
}
2. Executors.newFixedThreadPool(5);创建固定的线程池大小
package pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Demo01 {
public static void main(String[] args) {
ExecutorService threadExecutor =Executors.newFixedThreadPool(5);
try {
for (int i = 0; i <10 ; i++) {
threadExecutor.execute(()->{
System.out.println(Thread.currentThread().getName());
});
}
} catch (Exception e) {
e.printStackTrace();
}finally {
threadExecutor.shutdown();
}
}
}
3. Executors.newCachedThreadPool();创建可伸缩的线程,根据cpu开启线程
package pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Demo01 {
public static void main(String[] args) {
ExecutorService threadExecutor = Executors.newCachedThreadPool();
try {
for (int i = 1; i <10 ; i++) {
threadExecutor.execute(()->{
System.out.println(Thread.currentThread().getName());
});
}
} catch (Exception e) {
e.printStackTrace();
}finally {
threadExecutor.shutdown();
}
}
}