ExecutorService 和 NSOperationQueue
ExecutorService,简化了Android中的并发处理,NSOperationQueue简化了iOS中的并发处理。它们都管理线程池,作用十分相近,下面简单说明一下。
1.ExecutorService基本知识如下
An Executor
that provides methods to manage termination and methods that can produce a Future
for tracking progress of one or more asynchronous tasks.
An ExecutorService
can be shut down, which will cause it to reject new tasks.
Method submit
extends base method execute(Runnable)
by creating and returning a Future
that can be used to cancel execution and/or wait for completion. Methods invokeAny
and invokeAll
perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete.
继续学习请参考http://lavasoft.blog.51cto.com/62575/115112
从上面的地址中抄了一块简单的例子
package concurrent; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by IntelliJ IDEA. * * @author leizhimin 2008-11-25 14:28:59 */ public class TestCachedThreadPool { public static void main(String[] args) { // ExecutorService executorService = Executors.newCachedThreadPool(); ExecutorService executorService = Executors.newFixedThreadPool(5); // ExecutorService executorService = Executors.newSingleThreadExecutor(); for (int i = 0; i < 5; i++) { executorService.execute(new TestRunnable()); System.out.println("************* a" + i + " *************"); } executorService.shutdown(); } } class TestRunnable implements Runnable { public void run() { System.out.println(Thread.currentThread().getName() + "线程被调用了。"); while (true) { try { Thread.sleep(5000); System.out.println(Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } } }
2.NSOperationQueue基本知识如下
The NSOperationQueue
class regulates the execution of a set of NSOperation
objects.
Operation queues usually provide the threads used to run their operations. In OS X v10.6 and later, operation queues use the libdispatch
library (also known as Grand Central Dispatch) to initiate the execution of their operations. As a result, operations are always executed on a separate thread, regardless of whether they are designated as concurrent or non-concurrent operations.
学习Operation的使用, 请参考我的这篇文章 http://www.cnblogs.com/breezemist/p/4080749.html