Java Threads and the Concurrency Utilities 《读书笔记》

*       Java 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.
 * 
 *       Each Java application has a default main thread that executes the main() method. The
 *       application can also create threads to perform time-intensive tasks in the background so
 *       that it remains responsive to its users. These threads execute code sequences encapsulated
 *       in objects that are known as runnables.
 * 
 *       The Java virtual machine (JVM) gives each thread its own JVM stack to prevent
 *       threads from interfering with each other. Separate stacks let threads keep track of their next
 *       instructions to execute, which can differ from thread to thread. The stack also provides a
 *       thread with its own copy of method parameters, local variables, and return value.(线程安全)
 * 
 *       A Thread object is assigned a name, which is useful for debugging. Unless a name is
 *       explicitly specified, a default name that starts with the Thread- prefix is chosen.
 * 
 *       You can determine if a thread is alive or dead by calling Thread’s boolean isAlive()
 *       method. This method returns true when the thread is alive; otherwise, it returns false.
 * 
 *       A thread has an execution state that is identified by one of the Thread.State enum’s
 *       constants:
 *       • NEW: A thread that has not yet started is in this state.
 *       • RUNNABLE: A thread executing in the JVM is in this state.
 *       • BLOCKED: A thread that is blocked waiting for a monitor lock is in
 *       this state. (I’ll discuss monitor locks in Chapter 2.)
 *       • WAITING: A thread that is waiting indefinitely for another thread to
 *       perform a particular action is in this state.
 *       • TIMED_WAITING: A thread that is waiting for another thread to
 *       perform an action for up to a specified waiting time is in this state.
 *       • TERMINATED: A thread that has exited is in this state.
 *       Thread lets an application determine a thread’s current state by providing the
 *       Thread.State getState() method.
 * 
 *       When a computer has enough processors and/or processor cores, the computer’s
 *       operating system assigns a separate thread to each processor or core so the threads
 *       execute simultaneously. When a computer doesn’t have enough processors and/or cores,
 *       various threads must wait their turns to use the shared processors/cores.
 * 
 *       You can identify the number of processors and/or processor cores that are available
 *       to the JVM by calling the java.lang.Runtime class’s int availableProcessors() method.
 *       the return value could change during JVM execution and is never smaller than 1.
 * 
 *       Thread supports priority via its int getPriority() method, which returns the
 *       current priority, and its void setPriority(int priority) method, which sets the
 *       priority to priority. The value passed to priority ranges from Thread.MIN_PRIORITY
 *       to Thread.MAX_PRIORITY—Thread.NORMAL_PRIORITY identifies the default priority.
 * 
 *       Java lets you classify threads as daemon threads or nondaemon threads. A daemon thread
 *       is a thread that acts as a helper to a nondaemon thread and dies automatically when the
 *       application’s last nondaemon thread dies so that the application can terminate.
 *       By default, the threads associated with Thread objects are nondaemon threads. To
 *       create a daemon thread, you must call Thread’s void setDaemon(boolean isDaemon)
 *       method, passing true to isDaemon.
 * 
 *       An application will not terminate when the nondaemon default main thread
 *       terminates until all background nondaemon threads terminate. If the background threads
 *       are daemon threads, the application will terminate as soon as the default main thread
 *       terminates.
 */




 *       The Thread class provides an interruption mechanism in which one thread can interrupt
 *       another thread. When a thread is interrupted, it throws java.lang.InterruptedException.
 *       This mechanism consists of the following three methods:
 *       • void interrupt(): Interrupt the thread identified by the Thread
 *       object on which this method is called. When a thread is blocked
 *       because of a call to one of Thread’s sleep() or join() methods
 *       (discussed later in this chapter), the thread’s interrupted status is
 *       cleared and InterruptedException is thrown. Otherwise, the
 *       interrupted status is set and some other action is taken
 *       depending on what the thread is doing. (See the JDK
 *       documentation for the details.)
 *       • static boolean interrupted(): Test whether the current thread
 *       has been interrupted, returning true in this case. The interrupted
 *       status of the thread is cleared by this method.
 *       • boolean isInterrupted(): Test whether this thread has been
 *       interrupted, returning true in this case. The interrupted status of
 *       the thread is unaffected by this method.
 * 
 * 
 * 
 *       A thread (such as the default main thread) will occasionally start another thread to
 *       perform a lengthy calculation, download a large file, or perform some other timeconsuming activity. After finishing its other tasks, the thread that started the worker
 *       thread is ready to process the results of the worker thread and waits for the worker thread
 *       to finish and die.
 *       The Thread class provides three join() methods that allow the invoking thread to
 *       wait for the thread on whose Thread object join() is called to die:
 *       • void join(): Wait indefinitely for this thread to die.
 *       InterruptedException is thrown when any thread has
 *       interrupted the current thread. If this exception is thrown, the
 *       interrupted status is cleared.
 *       • void join(long millis): Wait at most millis milliseconds
 *       for this thread to die. Pass 0 to millis to wait indefinitely—
 *       the join() method invokes join(0). java.lang.
 *       IllegalArgumentException is thrown when millis is negative.
 *       InterruptedException is thrown when any thread has
 *       interrupted the current thread. If this exception is thrown, the
 *       interrupted status is cleared.
 *       • void join(long millis, int nanos): Wait at most millis
 *       milliseconds and nanos nanoseconds for this thread to die.
 *       IllegalArgumentException is thrown when millis is
 *       negative, nanos is negative, or nanos is greater than 999999.
 *       InterruptedException is thrown when any thread has
 *       interrupted the current thread. If this exception is thrown, the
 *       interrupted status is cleared.
 * 
 */



*       Developing multithreaded applications is much easier when threads don’t interact,
 *       typically via shared variables. When interaction occurs, various problems can arise that
 *       make an application thread-unsafe (incorrect in a multithreaded context).
 * 
 * 
 *       To boost performance, the compiler, the Java virtual machine (JVM), and the operating
 *       system can collaborate to cache a variable in a register or a processor-local cache, rather
 *       than rely on main memory. Each thread has its own copy of the variable. When one
 *       thread writes to this variable, it’s writing to its copy; other threads are unlikely to see the
 *       update in their copies.
 * 
 *       You can use synchronization to solve the previous thread problems. Synchronization is a
 *       JVM feature that ensures that two or more concurrent threads don’t simultaneously
 *       execute a critical section, which is a code section that must be accessed in a serial (one
 *       thread at a time) manner.
 *       This property of synchronization is known as mutual exclusion because each thread
 *       is mutually excluded from executing in a critical section when another thread is inside
 *       the critical section. For this reason, the lock that the thread acquires is often referred to as
 *       a mutex lock.
 *       Synchronization also exhibits the property of visibility in which it ensures that a
 *       thread executing in a critical section always sees the most recent changes to shared
 *       variables. It reads these variables from main memory on entry to the critical section and
 *       writes their values to main memory on exit.
 *       Synchronization is implemented in terms of monitors, which are concurrency
 *       constructs for controlling access to critical sections, which must execute indivisibly. Each
 *       Java object is associated with a monitor, which a thread can lock or unlock by acquiring
 *       and releasing the monitor’s lock (a token).
 * 
 *       Only one thread can hold a monitor’s lock. Any other thread trying to lock that
 *       monitor blocks until it can obtain the lock. When a thread exits a critical section, it
 *       unlocks the monitor by releasing the lock.
 *       Locks are designed to be reentrant to prevent deadlock (discussed later). When a
 *       thread attempts to acquire a lock that it’s already holding, the request succeeds.
 * 
 *       When synchronizing on an instance method, the lock is associated with the object
 *       on which the method is called.
 *       When synchronizing on a class method, the lock is associated with the java.lang.
 *       Class object corresponding to the class whose class method is called.
 * 
 *       Neither the Java language nor the JVM provides a way to prevent deadlock, and
 *       so the burden falls on you. the simplest way to prevent deadlock is to avoid having either a
 *       synchronized method or a synchronized block call another synchronized method/block.
 *       although this advice prevents deadlock from happening, it’s impractical because one of your
 *       synchronized methods/blocks might need to call a synchronized method in a Java api, and
 *       the advice is overkill because the synchronized method/block being called might not call any
 *       other synchronized method/block, so deadlock would not occur.
 * 
 * 
 *       You previously learned that synchronization exhibits two properties: mutual exclusion
 *       and visibility. The synchronized keyword is associated with both properties. Java also
 *       provides a weaker form of synchronization involving visibility only, and associates only
 *       this property with the volatile keyword.
 * 
 *       Because stopped has been marked volatile, each thread will access the main
 *       memory copy of this variable and not access a cached copy. The application will stop,
 *       even on a multiprocessor-based or a multicore-based machine.
 * 
 * 
 *       Use volatile only where visibility is an issue. also, you can only use this
 *       reserved word in the context of field declarations (you’ll receive an error if you try to make a
 *       local variable volatile). Finally, you can declare double and long fields volatile, but
 *       should avoid doing so on 32-bit JVMs because it takes two operations to access a double or
 *       long variable’s value, and mutual exclusion (via synchronized) is required to access their
 *       values safely.
 */



 *       Each ThreadLocal instance describes a thread-local variable, which is a variable that
 *       provides a separate storage slot to each thread that accesses the variable. You can think of
 *       a thread-local variable as a multislot variable in which each thread can store a different
 *       value in the same variable. Each thread sees only its value and is unaware of other threads
 *       having their own values in this variable.
 * 
 * 
 */



 *       Concurrency Utilities and Executors
 * 
 * 
 * 
 *       Java’s low-level thread capabilities let you create multithreaded applications that
 *       offer better performance and responsiveness over their single-threaded counterparts.
 *       However, performance issues that affect an application’s scalability and other problems
 *       resulted in Java 5’s introduction of the concurrency utilities.
 *       The concurrency utilities organize various types into three packages: java.util.
 *       concurrent, java.util.concurrent.atomic, and java.util.concurrent.locks.
 *       Basic types for executors, thread pools, concurrent hashmaps, and other high-level
 *       concurrency constructs are stored in java.util.concurrent; classes that support lockfree, thread-safe programming on single variables are stored in java.util.concurrent.
 *       atomic; and types for locking and waiting on conditions are stored in java.util.
 *       concurrent.locks.
 *       An executor decouples task submission from task-execution mechanics and
 *       is described by the Executor, ExecutorService, and ScheduledExecutorService
 *       interfaces. You obtain an executor by calling one of the utility methods in the Executors
 *       class. Executors are associated with callables and futures.
 */



 *       Countdown Latches 测试并发是不是很有用啊
 * 
 *       A countdown latch causes one or more threads to wait at a “gate” until another thread
 *       opens this gate, at which point these other threads can continue. It consists of a count and
 *       operations for “causing a thread to wait until the count reaches zero” and “decrementing
 *       the count.”
 *       The java.util.concurrent.CountDownLatch class implements the countdown latch
 *       synchronizer. You initialize a CountDownLatch instance to a specific count by invoking
 *       this class’s CountDownLatch(int count) constructor, which throws java.lang.
 *       IllegalArgumentException when the value passed to count is negative.
 */



 *       A cyclic barrier lets a set of threads wait for each other to reach a common barrier point.
 *       The barrier is cyclic because it can be reused after the waiting threads are released. This
 *       synchronizer is useful in applications involving a fixed-size party of threads that must
 *       occasionally wait for each other.
 */


*       Semaphores
 * 
 *       A semaphore maintains a set of permits for restricting the number of threads that can
 *       access a limited resource. A thread attempting to acquire a permit when no permits are
 *       available blocks until some other thread releases a permi.
 * 
 *       Semaphores whose current values can be incremented past 1 are known as
 *       counting semaphores, whereas semaphores whose current values can be only 0 or 1
 *       are known as binary semaphores or mutexes. in either case, the current value cannot be
 *       negative.
 * 
 *       Generally, semaphores used to control resource access should be initialized as fair,
 *       to ensure that no thread is starved out from accessing a resource. When using
 *       semaphores for other kinds of synchronization control, the throughput advantages of
 *       unfair ordering often outweigh fairness considerations.
 */



*       Java supports synchronization so that threads can safely update shared variables
 *       and ensure that a thread’s updates are visible to other threads. You leverage
 *       synchronization in your code by marking methods or code blocks with the
 *       synchronized keyword. These code sequences are known as critical sections.
 *       The Java virtual machine (JVM) supports synchronization via monitors and the
 *       monitorenter and monitorexit JVM instructions.
 * 
 * 
 *       Every Java object is associated with a monitor, which is a mutual exclusion (letting only
 *       one thread at a time execute in a critical section) construct that prevents multiple threads
 *       from concurrently executing in a critical section. Before a thread can enter a critical
 *       section, it’s required to lock the monitor. If the monitor is already locked, the thread
 *       blocks until the monitor is unlocked (by another thread leaving the critical section).
 *       When a thread locks a monitor in a multicore/multiprocessor environment, the
 *       values of shared variables that are stored in main memory are read into the copies
 *       of these variables that are stored in a thread’s working memory (also known as local
 *       memory or cache memory). This action ensures that the thread will work with the
 *       most recent values of these variables and not stale values, and is known as visibility.
 *       The thread proceeds to work with its copies of these shared variables. When the
 *       thread unlocks the monitor while leaving the critical section, the values in its copies
 *       of shared variables are written back to main memory, which lets the next thread
 *       that enters the critical section access the most recent values of these variables. (The
 *       volatile keyword addresses visibility only.)
 */



Java Threads and the Concurrency Utilities 电子版

下载地址:


http://yunpan.cn/c33Wu5GgPceP8  访问密码 0888


http://www.allitebooks.com/java-threads-and-the-concurrency-utilities/

你可能感兴趣的:(java,Java,Threads,and,the,Java,Threads,Java,Concurrency,Uti)