- 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();
- }
- }
- }
- 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
f1= pool.submit(new MyCallable(100)); - Future
f2= pool.submit(new MyCallable(200)); - Future
f3= pool.submit(new MyCallable(300)); - Future
f4= pool.submit(new MyCallable(400)); - // Future
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
{ - 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;
- }
- }