1. Processes and Threads
- Process: A running instance of a computer program that contains instructions to be executed, has its own independent address space, contains program content and data, and the address space of different processes is isolated from each other; the process has various resource and state information, including open files, subprocess, and signal processing.
- Threads: Represents the execution flow of a program, which is the basic unit of CPU scheduling execution, and threads have their own program counters, registers, stacks, and frames. Threads in the same process share the same address space while sharing memory and other resources that are owned by the process lock.
2. Multithreading
Multithreading is a mechanism that allows multiple instruction flows to be executed concurrently in a program, each of which is called a thread and is independent of each other. A thread, also known as a lightweight process, has independent execution control as a process, which is scheduled by the operating system, except that the thread does not have separate storage space, but rather shares a storage space with other threads in the owning process, which makes communication between threads much simpler than the process.
2.1 Thread implementations two ways
- Extended Java.lang.Thread Class
- Implementing the Java.lang.Runnable Interface
2.2 Advantages and disadvantages
Advantages of Multithreading:
- Better resource utilization
- Programming is easier in some cases
- Faster program Response
The cost of Multithreading:
- Design is more complex: While some multithreaded applications are simpler than single-threaded applications, others are generally more complex. This part of the code requires special attention when accessing shared data in multi-threaded access. The interaction between threads is often very complex. Incorrect thread synchronization produces errors that are very difficult to discover and reproduce to fix.
- The overhead of context switching: When the CPU switches from executing one thread to executing another, it needs to store the local data of the current thread, the program pointer, etc., and then load the local data of the other thread, the program pointer, and so on, before it starts executing. This switchover is called a "context switch". The CPU executes one thread in one context and then switches to another in the context of executing another thread. Context switching is not cheap. If it is not necessary, you should reduce the occurrence of context switches.
3. JVM Thread Scheduling
In a Java program, the JVM is responsible for thread scheduling. Thread scheduling is a value that assigns the use of CPU to multiple threads according to a specific mechanism.
There are two kinds of scheduling modes: time-sharing scheduling and preemptive scheduling.
- The time-sharing scheduling is that all threads take turns to gain CPU access, and evenly allocate each thread to occupy the CPU;
- Preemptive scheduling is based on the priority level of the thread to obtain the use of the CPU. The JVM's thread-scheduling pattern employs a preemptive pattern.
The so-called "concurrent execution" and "simultaneous" are not actually "simultaneous" in real sense. As we all know, the CPU has a clock frequency, indicating the number of times per second The CPU instructions can be executed. In each clock cycle, the CPU can actually only execute one (and possibly many) instructions. The operating system manages the process threads, and in turn (without a fixed order) allocates each process a short period of time (not necessarily evenly distributed), and then within each thread, the program code handles the internal thread's time allocation itself, switching between threads to execute, and the switching time is very short. So multitasking, multi-process, multi-threading is a kind of macroscopic feeling of the operating system, from the microscopic point of view, the operation of the program is executed asynchronously.4. State Transitions for Threads
1. New state: A new Thread object was created. 2. Ready state (Runnable): After the thread object is created, other threads call the object's start () method. The state of the thread is located in a pool of running threads that becomes operational and waits for the CPU to be used. 3, running State (Running): The ready state of the thread gets the CPU, executes the program code. 4, blocking State (Blocked): Blocking state is the thread for some reason to abandon the use of the CPU, temporarily stop running. Until the thread is in a ready state, the opportunity to go to the running state is reached. There are three types of blocking:
- Wait for blocking: The running thread executes the wait () method, and the JVM puts the thread into the waiting pool.
- Synchronous blocking: When a running thread acquires a synchronization lock on an object, the JVM puts the thread into the lock pool if the synchronization lock is occupied by another thread.
- Other blocking: The running thread executes the sleep () or join () method, or when an I/O request is made, the JVM will place the thread in a blocked state. When the sleep () state times out, join () waits for the thread to terminate or time out, or the I/O process finishes, the thread is re-entered in a ready state.
5. Dead State (Dead): The thread finishes executing or exits the run () method because of an exception, and the thread ends the life cycle.
5. Scheduling of Threads
1, adjust the thread priority: Java threads have priority, high priority threads will get more running opportunities.
The priority of a Java thread is expressed in integers, and the value range is the following three static constants for the 1~10,thread class:
- static int max_priority: The highest priority a thread can have, with a value of 10.
- static int min_priority: the lowest priority a thread can have, with a value of 1.
- static int norm_priority: The default priority assigned to the thread, with a value of 5.
the SetPriority () and GetPriority () methods of the thread class are used to set and get the priority of the thread, respectively. Each thread has a default priority. The default priority for the primary thread is thread.norm_priority. The priority of a thread has an inheritance relationship, such as the B thread created in a thread, then B will have the same priority as a. The JVM provides 10 thread priorities, but does not map well with common operating systems. If you want the program to be portable to each operating system, you should only use the thread class with the following three static constants as priority, which ensures that the same precedence is used for the same scheduling.
2, the thread sleep: thread.sleep (Long Millis) method, causes the thread to go to the blocking state. The Millis parameter sets the time to sleep, in milliseconds. When sleep is over, it becomes ready (Runnable) state. Sleep () platform portability is good.
3. Thread waits: The Wait () method in the object class causes the current thread to wait until another thread calls the Notify () method of this object or the Notifyall () Wake method. This two wake-up method is also a method in the object class, and behaves equivalent to calling wait (0).
4. Thread Concession: The Thread.yield () method pauses the currently executing thread object and gives the execution opportunity to the same or higher priority thread.
5, thread join: Join () method, wait for other threads to terminate. Invoking the Join () method of another thread in the current thread, the current thread goes into a blocking state until the other process finishes running, and the current thread is then turned into a ready state by blocking.
6. Thread Wakeup: The Notify () method in the object class that wakes up a single thread waiting on this objects monitor. If all threads are waiting on this object, then one of the threads is chosen to wake up. The choice is arbitrary and occurs when a decision is made on the implementation. The thread waits on the object's monitor by calling one of the wait methods. Until the current thread discards the lock on this object, it can continue to execute the awakened thread. The awakened thread competes with all other threads that are actively synchronizing on the object, for example, the thread that wakes up does not have a reliable privilege or disadvantage as the next thread that locks the object. A similar approach also has a notifyall () that wakes up all the threads waiting on this object monitor.
Note: Thread suspend () and resume () Two methods have been abolished in JDK1.5 and are no longer introduced. Because there is a deadlock tendency.
7. Common Thread noun explanation
- Main thread: The threads generated by the JVM Invoker Mian ().
- Current thread: This is an easy-to-confuse concept. Generally refers to the process obtained through Thread.CurrentThread ().
- Background thread: Refers to a thread that provides services to other threads, also known as a daemon thread. The garbage collection thread of the JVM is a background thread.
- Foreground thread: Refers to the thread that accepts the background thread service, in fact the foreground background thread is linked together, just like the puppet and the behind-the-scenes manipulator's relationship. The Puppet is the foreground thread and the behind-the-scenes manipulator is a background thread. The thread created by the foreground thread is also the foreground thread by default. You can use the Isdaemon () and Setdaemon () methods to determine and set whether a thread is a background thread.
6. Thread Blocking
In order to solve the access violation of the shared storage, Java introduced the synchronization mechanism, now let us examine the access of multiple threads to the shared resources, obviously the synchronization mechanism is not enough, because at any time the required resources are not necessarily ready to be accessed, in turn, the same time the resources prepared may be more than one. To address the problem of access control in this case, Java introduces support for blocking mechanisms.
Blocking refers to pausing a thread's execution to wait for a condition to occur (such as a resource is ready), and the classmate who learns the operating system must already be familiar with it. Java provides a number of ways to support blocking, let's analyze each of them.
- Sleep () Method: Sleep () allows you to specify a period of time in milliseconds as a parameter, which causes the thread to enter a blocking state within a specified time, cannot get CPU time, the specified time is over, and the thread re-enters the executable state. Typically, sleep () is used when waiting for a resource to be ready: After the test discovery condition is not met, let the thread block for a period of time and then re-test until the condition is satisfied.
- Suspend () and resume () methods: Two methods are used, suspend () causes the thread to enter a blocking state, and does not automatically recover, it must be called by its corresponding resume () to enable the thread to re-enter the executable state. Typically, suspend () and resume () are used when waiting for the result of another thread: After the test finds that the result has not yet been generated, the thread is blocked and the other thread produces the result, calling resume () to restore it.
- Yield () Method: Yield () causes the thread to discard the current CPU time, but does not cause the thread to block, that is, the thread is still in an executable state, and the CPU time may be split again at any time. The effect of calling yield () is equivalent to the scheduler thinking that the thread has performed enough time to go to another thread.
- Wait () and Notify () methods: Two methods are used, wait () causes the thread to enter the blocking state, it has two forms, one allows to specify a period of time in milliseconds as a parameter, and the other without parameters, the former when the corresponding notify () The thread re-enters the executable state when it is called or exceeds the specified time, and the latter must be called by the corresponding notify ().
Suspend () and resume ()
At first glance they have nothing to do with the suspend () and the Resume () methods, but in fact they are quite different. The core of the difference is that all of the methods described earlier, blocking will not release the lock (if occupied), and this pair of methods is the opposite. The core differences above lead to a series of differences in detail.
- First, all the methods described earlier are subordinate to the Thread class, but the pair is directly subordinate to the object class, which means that all objects have this pair of methods. At first glance this is very magical, but in fact it is very natural, because this pair of methods when blocking to release the lock occupied, and the lock is any object has, call any object's wait () method causes the thread to block, and the lock on the object is freed. The Notify () method that invokes an arbitrary object causes a randomly selected unblocking in the thread that is blocked by calling the wait () method of the object (but is not really executable until the lock is acquired).
- Second, all the methods described earlier can be called anywhere, but this pair of methods must be called in the Synchronized method or block, the reason is simple, only in the Synchronized method or block the current line friend occupy the lock, only the lock can be released. Similarly, locks on objects that call this pair of methods must be owned by the current thread, so that locks can be freed. Therefore, this pair of method calls must be placed in such a synchronized method or block where the locked object of the method or block is the object that invokes the pair of methods. If this condition is not met, the program can still compile, but the illegalmonitorstateexception exception will occur at run time.
Wait () and notify ()
The above characteristics of the wait () and notify () methods determine that they are often used with synchronized methods or blocks. A comparison between them and the operating system's interprocess communication mechanism reveals their similarity: the Synchronized method or block provides functionality similar to the operating system primitives, and their execution is not interfered by the multithreading mechanism, which is equivalent to blocks and wakeup Primitives (this pair of methods are declared as synchronized). Their combination allows us to implement an array of sophisticated inter-process communication algorithms (such as semaphore algorithms) on the operating system, and to solve a variety of complex inter-threading communication problems.
The Wait () and notify () methods are finally explained in two points:
- Calling the Notify () method causes the unblocked thread to be randomly selected from the thread that was blocked by calling the wait () method of the object, and we cannot predict which thread will be selected, so be careful when programming, and avoid problems with this uncertainty.
- In addition to notify (), there is also a method Notifyall () can also play a similar role, the only difference is that the call to the Notifyall () method will be called by the Wait () method of the object is blocked all at once unblocked all the threads. Of course, only the thread that gets the lock can go into the executable state.
Dead lock
When it comes to blocking, it is impossible to talk about deadlocks, and a brief analysis reveals that the suspend () method and the call to the Wait () method, which does not specify a time-out period, can generate a deadlock. Unfortunately, Java does not support deadlock avoidance at the language level, and we must be careful in programming to avoid deadlocks.
We have analyzed the various methods of threading blocking in Java, and we have focused on the wait () and notify () methods, because they are the most powerful and flexible to use, but it also makes them less efficient and prone to error. In practice we should use various methods flexibly in order to achieve our goal better.
7. Daemon Thread
A daemon thread is a special kind of thread that differs from a normal thread in that it is not a core part of the application, and that when all non-daemons of an application terminate the run, the application terminates even if there is still a daemon thread running, and the application will not terminate as long as there is a non-daemon thread running. A daemon thread is typically used to service other threads in the background.
You can call method Isdaemon () to determine whether a thread is a daemon thread, or you can call method Setdaemon () to Cheng a line as a daemon thread.
8. Thread Group
Thread groups are a Java-specific concept in Java where thread groups are objects of class Threadgroup, each of which is subordinate to the only thread group, which is specified during thread creation and cannot be changed during the entire lifetime of the process. You can specify a thread group that belongs to threads by calling the Threadgroup class constructor that contains the type parameter, and, if not specified, the thread defaults to the system thread group named system.
In Java, all thread groups must be explicitly created in addition to the pre-built system thread group. In Java, each thread group other than the system thread group is subordinate to another thread group, and you can specify the thread group to which it belongs when you create the thread group, which, if not specified, is subordinate to the system thread group by default. In this way, all thread groups make up a tree that is rooted in the system thread group.
Java allows us to operate on all threads in a thread group at the same time, for example, by invoking the appropriate method of the thread group to prioritize all of them, or to start or block all threads in it.
Another important role of the thread group mechanism of Java is thread safety. The thread group mechanism allows us to differentiate between threads with different security features by grouping, to handle different groups of threads differently, and to support the adoption of incorrect security measures through the hierarchical structure of thread groups. The Java Threadgroup class provides a number of ways to make it easier for us to operate on each thread group in the thread group tree and on each thread in the thread group.
Related reading thread synchronization method, Java four thread pool, Java memory model
http://lavasoft.blog.51cto.com/62575/27069/
Http://www.cnblogs.com/dolphin0520/p/3920373.html
Http://www.cnblogs.com/luxiaoxun/p/3870265.html
http://programming.iteye.com/blog/158568
Multithreaded Programming--java