代码
public class TestThreadPoolExecutor2 {
public static void main ( String [ ] args) {
int corePoolSize = 5 ;
int maximumPoolSize = 10 ;
long keepAliveTime = 10 ;
TimeUnit timeUnit = TimeUnit . SECONDS;
BlockingQueue workQueue = new ArrayBlockingQueue < > ( 5 ) ;
ThreadPoolExecutor. AbortPolicy abortPolicy = new ThreadPoolExecutor. AbortPolicy ( ) ;
ThreadPoolExecutor. CallerRunsPolicy callerRunsPolicy = new ThreadPoolExecutor. CallerRunsPolicy ( ) ;
ThreadPoolExecutor. DiscardOldestPolicy discardOldestPolicy = new ThreadPoolExecutor. DiscardOldestPolicy ( ) ;
ThreadPoolExecutor. DiscardPolicy discardPolicy = new ThreadPoolExecutor. DiscardPolicy ( ) ;
ThreadPoolExecutor executorA = new ThreadPoolExecutor (
corePoolSize, maximumPoolSize, keepAliveTime, timeUnit, workQueue, new NamedThreadFactory ( "AAAAA" ) , abortPolicy) ;
ThreadPoolExecutor executorB = new ThreadPoolExecutor (
corePoolSize, maximumPoolSize, keepAliveTime, timeUnit, workQueue, new NamedThreadFactory ( "BBBBB" ) , abortPolicy) ;
Future < Object > futureA = executorA. submit ( new Callable < Object > ( ) {
@Override
public Object call ( ) throws Exception {
System . out. println ( "A" ) ;
return null ;
}
} ) ;
boolean cancelA = futureA. cancel ( true ) ;
System . out. println ( "A是否取消:" + cancelA) ;
Future < Object > futureB = executorB. submit ( new Callable < Object > ( ) {
@Override
public Object call ( ) throws Exception {
System . out. println ( "B" ) ;
return null ;
}
} ) ;
boolean cancelB = futureB. cancel ( true ) ;
System . out. println ( "B是否取消:" + cancelB) ;
executorA. shutdown ( ) ;
executorB. shutdown ( ) ;
}
static class NamedThreadFactory implements ThreadFactory {
private final AtomicInteger poolNumber = new AtomicInteger ( 1 ) ;
private final ThreadGroup threadGroup;
private final AtomicInteger threadNumber = new AtomicInteger ( 1 ) ;
public final String namePrefix;
NamedThreadFactory ( String name) {
SecurityManager s = System . getSecurityManager ( ) ;
threadGroup = ( s != null ) ? s. getThreadGroup ( ) :
Thread . currentThread ( ) . getThreadGroup ( ) ;
if ( null == name || "" . equals ( name. trim ( ) ) ) {
name = "pool" ;
}
namePrefix = name + "-" +
poolNumber. getAndIncrement ( ) +
"-thread-" ;
}
@Override
public Thread newThread ( Runnable r) {
Thread t = new Thread ( threadGroup, r,
namePrefix + threadNumber. getAndIncrement ( ) ,
0 ) ;
if ( t. isDaemon ( ) )
t. setDaemon ( false ) ;
if ( t. getPriority ( ) != Thread . NORM_PRIORITY)
t. setPriority ( Thread . NORM_PRIORITY) ;
return t;
}
}
}
结果