JAVA线程——选自《Learn Java for Android Development》

来源:互联网 发布:电脑软件怎么清除数据 编辑:程序博客网 时间:2024/06/11 20:00

本文选自《Learn Java for Android Development》中"Thread API"一节。见它对线程的介绍简洁又清晰,自己虽然英语很差,但这一段浅显易懂的文字还是看明白了,就记了下来。


Applications execute via threads, which are independent paths of execution through an application's code. When multiple threads are executing, each thread's path can differ from other thread paths. For example, a thread might execute one of a switch statement's cases, and another thread might execute another of this statement's cases.

NOTE:Applications use threads to improve performance. Some appications can get by with only the default main thread to carry out their tasks, but other applications need additional threads to perform time-intensive tasks in the background, so that they remain responsive to their users.

The virtual machine gives each thread its own method-call stack to prevent threads from interfering with each other. Separate stacks let threads keep track of their next instructions to execute, which can fiffer from thread to thread. The stack also provides a thread with its own copy of method parameters, local variables, and return value.

Java supports thread via its Threading API. This API consists of one interface (Runnable) and four classes(Thread, ThreadGroup, ThreadLocal, and InheritableThreadLocal) int the java.lang package. After exploring Runnable and Thread(and mentioning ThreadGroup during this exploration), this section explores thread synchronization, ThreadLocal, and InheritableThreadLocal.

NOTE: Java verision 5 introduced the java.util.concurrent package as a high-level alternative to the low-level Threading API. (I will discuss this package in Chapter 9.) Althrough java.util.concurrent is the preferred API for working with threads. you should also be somewhat familiar with Threading because it is helpful in simple threading scenarios. Also, you might have to analyze someone else's source code that depends on Threading.