1:处理Runnable 任务的方法
package ThreadPooITest;
import java.util.concurrent.*;
//目标:线程池创建
public class ThreadPoolTest {
public static void main(String[] args) {
//1:通过ThreadPoolExector
ExecutorService pool= new ThreadPoolExecutor(3, 5, 8, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(4),Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
MyRunnble myRunnble = new MyRunnble();
/* pool.execute(myRunnble);//线程池自动创建一个新的线程 。自动处理这个任务 自动执行
pool.execute(myRunnble);//线程池自动创建一个新的线程 。自动处理这个任务 自动执行
pool.execute(myRunnble);//线程池自动创建一个新的线程 。自动处理这个任务 自动执行
pool.execute(myRunnble);//复用前面核心线程
pool.execute(myRunnble);//复用前面核心线程
*/
pool.execute(myRunnble);//线程池自动创建一个新的线程 。自动处理这个任务 自动执行
pool.execute(myRunnble);//线程池自动创建一个新的线程 。自动处理这个任务 自动执行
pool.execute(myRunnble);//线程池自动创建一个新的线程 。自动处理这个任务 自动执行
pool.execute(myRunnble);
pool.execute(myRunnble);
pool.execute(myRunnble);
pool.execute(myRunnble);
//到了临时线程的创建时机了
pool.execute(myRunnble);
pool.execute(myRunnble);
//看到新任务的拒绝的时机了
pool.execute(myRunnble);
// pool.shutdown();//等待线程都跑完再关闭线程池
// pool.shutdownNow(); //立刻关闭线程池
}
}
package ThreadPooITest;
public class MyRunnble implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"==> 输出666~~");
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2:处理callable任务
package ThreadPooITest;
import java.util.concurrent.*;
//目标:线程池创建
public class ThreadPoolTest1 {
public static void main(String[] args) throws Exception, InterruptedException {
//1:通过ThreadPoolExector
ExecutorService pool= new ThreadPoolExecutor(3, 5, 8, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(4),Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
Future<String> f1= pool.submit(new MyCallable(100));
Future<String> f2= pool.submit(new MyCallable(200));
Future<String> f3= pool.submit(new MyCallable(300));
Future<String> f4= pool.submit(new MyCallable(400));
// Future<String> f5= pool.submit(new MyCallable(500));
System.out.println(f1.get());
System.out.println(f2.get());
System.out.println(f3.get());
System.out.println(f4.get());
}
}
package ThreadPooITest;
import java.util.concurrent.Callable;
public class MyCallable implements Callable<String> {
private int n;
public MyCallable(int n){
this.n=n;
}
@Override
public String call() throws Exception {
int sum=0;
for (int i=1;i<=n;i++){
sum+=i;
}
return Thread.currentThread().getName() +"线程求1-"+n+"的和是:"+sum;
}
}