package com.threadpooltest; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import android.app.Activity; import android.os.Bundle; import android.text.format.Formatter; import android.util.Log; import com.threadpooltest.util.CommonThreadPoolExector; import com.threadpooltest.util.CommonThreadPoolFactory; import com.threadpooltest.util.RunTimeConstant; public class MainActivity extends Activity { private static final String TAG = "ThreadTest"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.i(TAG, "CPU "+RunTimeConstant.CURRENT_PROCESSOR_COUNT); Log.i(TAG, "avaiable "+Formatter.formatFileSize(this, RunTimeConstant.MEMORY_AVAILABLE)); Log.i(TAG, "max "+Formatter.formatFileSize(this, RunTimeConstant.MEMORY_MAX)); Log.i(TAG, "total "+Formatter.formatFileSize(this, RunTimeConstant.MEMORY_TOTAL)); // for (int i = 0; i < 10; i++) { // //用submit可以有返回值,用execute没有返回值 ,但是,如果你直接提交一个Runable也不会得到想要的返回值,要用Callable //// CommonThreadPoolFactory.getDefaultExecutor().submit(runnable); // Future<String> future = CommonThreadPoolFactory.getDefaultExecutor().submit(callable); // try { // System.out.println(future.get()); // } catch (InterruptedException e) { // e.printStackTrace(); // } catch (ExecutionException e) { // e.printStackTrace(); // } // } //上面的想要获得数据只能是同步的,这样非常不好,想要异步获取数据怎么办,线程池去执行任务,一旦有一个执行完就打出一个, //那么就使用CompleteService,它限制于数据已知的请示,如果未知也没招。 CompletionService<String> completionService = new ExecutorCompletionService<String>(new CommonThreadPoolExector(Executors.defaultThreadFactory())); for (int i = 0; i < 10; i++) { completionService.submit(callable); } for (int i = 0; i < 10; i++) { try { System.out.println(completionService.take().get()+" "+i); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } CommonThreadPoolFactory.shutDownAllPools(); } Callable<String> callable = new Callable<String>() { @Override public String call() throws Exception { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } Log.i(TAG, "斑马斑马"); return "erbai"; } }; Runnable runnable = new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } Log.i(TAG, "斑马斑马"); } }; @Override public void onBackPressed() { CommonThreadPoolFactory.shutDownAllPools(); super.onBackPressed(); }; }
<pre name="code" class="java">package com.threadpooltest.util; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; public class CommonThreadPoolFactory { private static volatile ScheduledExecutorService threadPoolExecutor; public static final ScheduledExecutorService getDefaultExecutor() { if (threadPoolExecutor == null) { synchronized (CommonThreadPoolFactory.class) { ThreadFactory sThreadFactory = new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setPriority(Thread.MIN_PRIORITY); return t; } }; threadPoolExecutor = new CommonThreadPoolExector(sThreadFactory); } } return threadPoolExecutor; } public static void shutDownAllPools(){ if (threadPoolExecutor != null) { threadPoolExecutor.shutdown(); threadPoolExecutor = null; } } }
package com.threadpooltest.util; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class CommonThreadPoolExector extends ScheduledThreadPoolExecutor { private static final int CORE_POOL_SIZE = RunTimeConstant.CURRENT_PROCESSOR_COUNT + 1; private static final int MAXIMUM_POOL_SIZE = RunTimeConstant.CURRENT_PROCESSOR_COUNT * 2 + 1; private static final int KEEP_ALIVE = 1; private static final RejectedExecutionHandler handler = new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { } }; public CommonThreadPoolExector(ThreadFactory threadFactory) { super(CORE_POOL_SIZE, threadFactory, handler); super.setKeepAliveTime(KEEP_ALIVE, TimeUnit.SECONDS); super.setMaximumPoolSize(MAXIMUM_POOL_SIZE); } CommonThreadPoolExector(int corePoolSize, int maxSize, int keepAliveSeconds, ThreadFactory threadFactory, RejectedExecutionHandler handler) { super(corePoolSize, threadFactory, handler); super.setKeepAliveTime(keepAliveSeconds, TimeUnit.SECONDS); super.setMaximumPoolSize(maxSize); } @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); } @Override protected void terminated() { super.terminated(); } }
package com.threadpooltest.util; public class RunTimeConstant { public static final Runtime CURRENT_RUNTIME = Runtime.getRuntime(); //手机共有几个内核 public static final int CURRENT_PROCESSOR_COUNT = CURRENT_RUNTIME.availableProcessors(); public static final long MEMORY_AVAILABLE = CURRENT_RUNTIME.freeMemory(); public static final long MEMORY_MAX = CURRENT_RUNTIME.maxMemory(); public static final long MEMORY_TOTAL = CURRENT_RUNTIME.totalMemory(); }