一、線程
成都創新互聯公司堅持“要么做到,要么別承諾”的工作理念,服務領域包括:網站建設、網站設計、企業官網、英文網站、手機端網站、網站推廣等服務,滿足客戶于互聯網時代的招遠網站設計、移動媒體設計的需求,幫助企業找到有效的互聯網解決方案。努力成為您成熟可靠的網絡建設合作伙伴!
在Android開發中,你不可能都在主線程中開發,畢竟要聯網,下載數據,保存數據等操作,當然這就離不開線程。
(當然你可以在Android4.0以前的手機里在主線程請求網絡,我最早開發的時候,用的手機比較古老。。。)
在Android中你可以隨意創建線程,于是就會造成線程不可控,內存泄漏,創建線程消耗資源,線程太多了消耗資源等問題。
具體線程怎么創建我就不在文章里描述了,畢竟這主要將并發編程。。。。
大家知道線程不可控就好了。。。于是就需要對線程進行控制,防止一系列問題出現,這就用到了如下要講的東西。
二、線程池
線程池:顧名思義,就是放線程的大池子。
如何創建一個線程池?
先說說幾個系統的線程池:
這幾個線程池不做多余闡述,因為這些線程池的原理都與我下面要講的有關。。。。
如何自定義線程池(先來了解幾個必須知道的參數):
corePoolSize:
核心線程池大小,線程池中主要工作的線程的多少。
maximumPoolSize:
線程池最大線程數。
keepAliveTime:
空閑線程可保持的時間是多久,如果你啟用了allowCoreThreadTimeOut方法,你的線程池里的空閑線程在這個時間段后會自動銷毀,如果沒啟用,則只要不超過corePoolSize,空閑線程也不會銷毀。
Unit:
keepAliveTime的時間單位
workQueue:
阻塞隊列,當任務達到corePoolSize,就會被放入這個隊列
常見幾種BlockingQueue實現
threadFactory:
線程工廠,主要用來創建線程;
handler:
表示當拒絕處理任務時的策略,也就是參數maximumPoolSize達到后丟棄處理的方法。有以下四種取值:
用戶也可以實現接口RejectedExecutionHandler定制自己的策略。
代碼展示:
//線程工廠 public class TaskThreadFactory implements ThreadFactory { private final AtomicInteger mThreadNumber = new AtomicInteger(1); private final String mNamePrefix; TaskThreadFactory(String name) { mNamePrefix = name + "#"; } public Thread newThread(Runnable r) { Thread t = new Thread(r,mNamePrefix + mThreadNumber.getAndIncrement()); // if (t.isDaemon()) // t.setDaemon(false); // // if (t.getPriority() != Thread.NORM_PRIORITY) // t.setPriority(Thread.NORM_PRIORITY); return t; } } //重寫runnable public class PRunnable implements Runnable { public static final int HIGH = 1;//優先級高 public static final int NORMAL = 2;//優先級中等 public static final int LOW = 3;//優先級低 @IntDef({HIGH,NORMAL,LOW}) @Retention(RetentionPolicy.SOURCE) public @interface Priority{} public final int priority; private final Runnable runnable; public int serial; public PRunnable(Runnable runnable){ this(NORMAL,runnable); } public PRunnable(@Priority int priority,Runnable runnable){ this.priority = priority; this.runnable = runnable; } @Override public void run() { if (runnable != null) { runnable.run(); } } /** * 線程隊列方式 先進先出 * @param r1 * @param r2 * @return */ public static final int compareFIFO(PRunnable r1, PRunnable r2) { int result = r1.priority-r2.priority; return result==0?r1.serial-r2.serial:result; } /** * 線程隊列方式 后進先出 * @param r1 * @param r2 * @return */ public static final int compareLIFO(PRunnable r1, PRunnable r2) { int result = r1.priority-r2.priority; return result==0?r2.serial-r1.serial:result; } } //線程池實現 public class TaskExecutor implements Executor { private final static int QUEUE_INIT_CAPACITY = 20; private static final int CORE = 3; private static final int MAX = 5; private static final int TIMEOUT = 30 * 1000; private AtomicInteger SERIAL = new AtomicInteger(0);//主要獲取添加任務 public static class Config { public int core; public int max; public int timeout; public boolean allowCoreTimeOut; public boolean fifo; public Config(int core, int max, int timeout, boolean allowCoreTimeOut,boolean fifo) { this.core = core; this.max = max; this.timeout = timeout; this.allowCoreTimeOut = allowCoreTimeOut; this.fifo = fifo; } } public static Config defaultConfig = new Config(CORE, MAX, TIMEOUT, true,true); private final String name; private final Config config; private ExecutorService service; public TaskExecutor(String name) { this(name, defaultConfig); } public TaskExecutor(String name, Config config) { this(name, config, true); } public TaskExecutor(String name, Config config, boolean startup) { this.name = name; this.config = config; if (startup) { startup(); } } public void startup() { synchronized (this) { if (service != null && !service.isShutdown()) { return; } service = createExecutor(config); } } public void shutdown() { ExecutorService executor = null; synchronized (this) { // 交換變量 if (service != null) { executor = service; service = null; } } if (executor != null) { // 停止線程 if (!executor.isShutdown()) { executor.shutdown(); } // 回收變量 executor = null; } } private void executeRunnable(PRunnable runnable) { synchronized (this) { if (service == null || service.isShutdown()) { return; } runnable.serial = SERIAL.getAndIncrement(); service.execute(runnable); } } @Override public void execute(Runnable runnable) { if (runnable instanceof PRunnable) { executeRunnable((PRunnable) runnable); }else{ executeRunnable(new PRunnable(runnable)); } } public Future<?> submit(Runnable runnable) { synchronized (this) { if (service == null || service.isShutdown()) { return null; } if (runnable instanceof PRunnable) { ((PRunnable) runnable).serial = SERIAL.getAndIncrement(); return service.submit(runnable); }else{ PRunnable pRunnable = new PRunnable(runnable); pRunnable.serial = SERIAL.getAndIncrement(); return service.submit(pRunnable); } } } public void execute(Runnable runnable, @PRunnable.Priority int priority) { executeRunnable(new PRunnable(priority,runnable)); } private ExecutorService createExecutor(Config config) { ThreadPoolExecutor service = new ThreadPoolExecutor(config.core, config.max, config.timeout, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(QUEUE_INIT_CAPACITY, config.fifo ? mQueueFIFOComparator : mQueueLIFOComparator), new TaskThreadFactory(name), new ThreadPoolExecutor.DiscardPolicy()); allowCoreThreadTimeOut(service, config.allowCoreTimeOut); return service; } public boolean isBusy() { synchronized (this) { if (service == null || service.isShutdown()) { return false; } if(service instanceof ThreadPoolExecutor){ ThreadPoolExecutor tService = (ThreadPoolExecutor) service; return tService.getActiveCount() >= tService.getCorePoolSize(); } return false; } } private static final void allowCoreThreadTimeOut(ThreadPoolExecutor service, boolean value) { if (Build.VERSION.SDK_INT >= 9) { allowCoreThreadTimeOut9(service, value); } } @TargetApi(9) private static final void allowCoreThreadTimeOut9(ThreadPoolExecutor service, boolean value) { service.allowCoreThreadTimeOut(value); } Comparator<Runnable> mQueueFIFOComparator = new Comparator<Runnable>() { @Override public int compare(Runnable lhs, Runnable rhs) { PRunnable r1 = (PRunnable) lhs; PRunnable r2 = (PRunnable) rhs; return PRunnable.compareFIFO(r1, r2); } }; Comparator<Runnable> mQueueLIFOComparator = new Comparator<Runnable>() { @Override public int compare(Runnable lhs, Runnable rhs) { PRunnable r1 = (PRunnable) lhs; PRunnable r2 = (PRunnable) rhs; return PRunnable.compareLIFO(r1, r2); } }; }
以上所述是小編給大家介紹的Android開發經驗談:并發編程(線程與線程池)詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對創新互聯網站的支持!
當前題目:Android開發經驗談:并發編程(線程與線程池)(推薦)
路徑分享:http://vcdvsql.cn/article4/gjehoe.html
成都網站建設公司_創新互聯,為您提供搜索引擎優化、域名注冊、云服務器、用戶體驗、定制網站、虛擬主機
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯