?
?
?
?
package com.itheima.d8_threadpool;
public class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + "输出了: HelloWorld ==>" + i);
}
try {
System.out.println(Thread.currentThread().getName() + "本任务与线程绑定了,线程进入了休眠了~~~");
Thread.sleep(10000000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.itheima.d8_threadpool;
import java.util.concurrent.*;
/**
* 目标:自定义一个线程池对象,并测试其特性。
*
*/
public class ThreadPoolDemo1 {
public static void main(String[] args) {
//1.创建线程池对象
// public ThreadPoolExecutor (int corePoolSize,
// * int maximumPoolSize,
// * long keepAliveTime,
// * TimeUnit unit,
// * BlockingQueue<Runnable> workQueue,
// * ThreadFactory threadFactory,
// * RejectedExecutionHandler handler)
ExecutorService pool = new ThreadPoolExecutor(3,5,
6,TimeUnit.SECONDS,new ArrayBlockingQueue<>(5),Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy() );
//2.给任务线程池处理。
Runnable target = new MyRunnable();
pool.execute(target);
pool.execute(target);
pool.execute(target);
pool.execute(target);
pool.execute(target);
pool.execute(target);
pool.execute(target);
pool.execute(target);
//创建临时线程
pool.execute(target);
pool.execute(target);
//不创建 拒绝策略被触发!!
// pool.execute(target);
//关闭线程池(开发中一般不会使用)
// pool.shutdownNow();//立即关闭,即使任务没有完成,丢失任务的!
pool.shutdownNow();//会等待全部任务执行完毕之后再关闭(建议使用的)
}
}
?
?
package com.itheima.d8_threadpool;
import java.util.concurrent.Callable;
/**
* 1.定义一个任务类 实现Callable 接口 应该申明线程任务执行完毕后的结果的数据类型
*/
public class MyCallable implements Callable<String> {
private int n ;
public MyCallable(int n ){this.n = n;}
/**
* 2.重写call方法(任务方法)
* @return
* @throws Exception
*/
@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;
}
}
package com.itheima.d8_threadpool;
import java.util.concurrent.*;
/**
* 目标:自定义一个线程池对象,并测试其特性。
*
*/
public class ThreadPoolDemo2 {
public static void main(String[] args) throws Exception {
//1.创建线程池对象
// public ThreadPoolExecutor (int corePoolSize,
// * int maximumPoolSize,
// * long keepAliveTime,
// * TimeUnit unit,
// * BlockingQueue<Runnable> workQueue,
// * ThreadFactory threadFactory,
// * RejectedExecutionHandler handler)
ExecutorService pool = new ThreadPoolExecutor(3,5,
6,TimeUnit.SECONDS,new ArrayBlockingQueue<>(5),Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy() );
//2.给任务线程池处理。
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));
// String rs = f1.get();
// System.out.println(rs);
System.out.println(f1.get());
System.out.println(f2.get());
System.out.println(f3.get());
System.out.println(f4.get());
System.out.println(f5.get());
}
}
?
|