package com.example.foraddapptest;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
public class ExecutorHelper {
private final ThreadLocal<Boolean> WORK_THREAD_FLAG = new ThreadLocal<>();
private final String mThreadNamePre /*= "LearnToolModel-thread-"*/;
private final Executor mExecutor;
public ExecutorHelper(String threadNamePre, int nThreads){
if(threadNamePre == null || nThreads < 1){
throw new IllegalArgumentException("threadNamePre = " + threadNamePre +
", nThreads = " + nThreads);
}
mThreadNamePre = threadNamePre;
mExecutor = Executors.newFixedThreadPool(nThreads,
new ThreadFactory() {
AtomicInteger threadNumber = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
String threadName = mThreadNamePre + threadNumber.getAndIncrement();
Runnable wrapRunner = new Runnable() {
@Override
public void run() {
WORK_THREAD_FLAG.set(true);
r.run();
}
};
Thread thread = new Thread(wrapRunner, threadName);
//WORK_THREAD_FLAG.set(true);
System.out.println("newThread run on " + Thread.currentThread().getName());
return thread;
}
});
}
public void runOnWorkThread(Runnable runnable) {
if ( isWorkThread() ) {
runnable.run();
} else {
mExecutor.execute(runnable);
}
}
public boolean isWorkThread() {
Boolean flag = WORK_THREAD_FLAG.get();
if (flag != null && Boolean.TRUE.equals(flag)) {
final String threadName = Thread.currentThread().getName();
if(!threadName.startsWith(mThreadNamePre)){
System.err.println("isWorkThread() return true, name not match : " +
threadName );
}
System.out.println("isWorkThread() return true");
return true;
}
System.err.println("isWorkThread() return false, " + Thread.currentThread());
return false;
}
public static void main(String[] args){
final ExecutorHelper executorHelper = new ExecutorHelper("test-", 1);
executorHelper.runOnWorkThread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
executorHelper.runOnWorkThread(()->{
System.out.println("Thread.currentThread().getName()..1..");
});
executorHelper.runOnWorkThread(()->{
System.out.println("Thread.currentThread().getName()..2..");
});
executorHelper.runOnWorkThread(()->{
System.out.println("Thread.currentThread().getName()..3..");
});
}
});
executorHelper.runOnWorkThread(()->{
System.out.println("22222222");
});
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}