Application Fundamentals--Thread-safe methods(线程安全方法)

Thread-safe methods--线程安全方法

In a few contexts, the methods you implement may be called from more than one thread, and therefore must be written to be thread-safe. 翻译:某些场景下,方法的实现需要考虑线程安全。

This is primarily true for methods that can be called remotely — as in the RPC mechanism discussed in the previous section. When a call on a method implemented in an IBinder object originates in the same process as the IBinder, the method is executed in the caller's thread. However, when the call originates in another process, the method is executed in a thread chosen from a pool of threads that Android maintains in the same process as the IBinder; it's not executed in the main thread of the process. For example, whereas a service's onBind() method would be called from the main thread of the service's process, methods implemented in the object that onBind() returns (for example, a Stub subclass that implements RPC methods) would be called from threads in the pool. Since services can have more than one client, more than one pool thread can engage the same IBinder method at the same time. IBinder methods must, therefore, be implemented to be thread-safe.

翻译:那些需要被远程调用的方法是必须支持线程安全的。当我们调用源于同一个进程中创建的IBinder对象的方法的时候,方法的执行和调用是处于一个线程的。但是,对于远程调用而言,调用是源于另外一个进程的,被调用方法是一个特定线程中执行,这个线程来自IBinder对象所属进程维护的线程池(Android系统负责维护)中的一个线程的时候,被调用方法运行所处的线程不是当前IBinder对象所属进程的主线程。比如说,服务的onBind()方法从这个服务进程下的主线程中被调用的,而服务的onBind()方法所返回对象(实现RPC接口的Stub子类实例)是属于线程池中的某个线程,由于服务是可以有多个客户端的,线程池中多个线程可以提供对一个 IBinder实例的一个方法被多个客户端程序同时调用的需要,所以说IBinder接口中的远程方法的实现都必须支持线程安全的。

Similarly, a content provider can receive data requests that originate in other processes. Although the ContentResolver and ContentProvider classes hide the details of how the interprocess communication is managed, ContentProvider methods that respond to those requests — the methods query(), insert(), delete(), update(), and getType() — are called from a pool of threads in the content provider's process, not the main thread of the process. Since these methods may be called from any number of threads at the same time, they too must be implemented to be thread-safe.

翻译:同样,内容提供组件可以接受来自其他进程的数据请求,尽管ContentResolver 和 ContentProvider类都隐藏了很多底层通讯细节,query(), insert(), delete(), update(), 和 getType() 都是在内容提供组件所属进程下的线程池中的某个线程中执行的,所以它们都必须支持线程安全。

你可能感兴趣的:(thread,android)