juc 线程池

package threadPool;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

import java.util.concurrent.ScheduledExecutorService;

import javax.sql.PooledConnection;

/*

 * 线程池

 * 

 */

public class ThreadPool {

public static void main(String[] args) throws InterruptedException, ExecutionException {

//创建固定大小的线程池

ExecutorService es=Executors.newFixedThreadPool(5);

/*

//缓存线程池,数量不固定,根据需求自动更改数量

ExecutorService es=Executors.newCachedThreadPool();

//创建单个线程池,只有一个线程

ExecutorService es=Executors.newSingleThreadExecutor();

//创建固定大小的线程,可以延迟或定时的执行任务

ScheduledExecutorService es=Executors.newScheduledThreadPool(5);

*/

/*//
Future<Integer> future= es.submit(new Callable<Integer>() {

//

//
@Override

//
public Integer call() throws Exception {

//
// TODO Auto-generated method stub

//

//
int sum=0;

//
for (int i = 0; i <10; i++) {

//
sum+=i;

//
}

//
return sum;

//
}

//
});

//
System.out.println(future.get());

//
es.shutdown();

*/

ThreadPoolDemo td=new ThreadPoolDemo();

//为线程池中的线程分配任务

for (int i = 0; i < 10; i++) {

es.submit(td);

}

//关闭线程池

es.shutdown();

}

}

class ThreadPoolDemo implements Runnable{

private int i=0;

@Override

public void run() {

// TODO Auto-generated method stub

while(i<=100) {

System.out.println(Thread.currentThread().getName()+”:”+i++);

}

}

}

ScheduledThreadPool  使用

package threadPool;

import java.sql.Time;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class newScheduledThreadPool {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ScheduledExecutorService pool=Executors.newScheduledThreadPool(5);
for (int i = 0; i < 5; i++) {
Future<Integer> result=pool.schedule(new Callable<Integer>() {

@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
int num=new Random().nextInt(100);
System.out.println(Thread.currentThread().getName()+”:”+num);
return num;
}


}, 1, TimeUnit.SECONDS);
System.out.println(result.get());
}
pool.shutdown();
}
}

    原文作者:JUC
    原文地址: https://blog.csdn.net/qq_38718211/article/details/79095042
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞