System learning java high concurrency series two

Reprinted, please indicate the original source, thank you!

What is thread?

A thread is an entity of a process that is the basic unit of CPU scheduling and dispatching. It is a smaller unit that can run independently than a process. Basically do not have their own thread of system resources, only a little essential in the operation of the resources (such as the program counter, a set of registers and stack), but it can be used with other threads belong to a process of sharing all resources owned by the process.


System learning java high concurrency series two
  1. New state (New): a thread object is created.
  2. Ready state (Runnable): after the thread object is created, other threads call the object’s start () method. The thread in that state is running in the running thread pool and becomes operational, waiting for access to CPU.
  3. Run status (Running): the ready state thread gets the CPU and executes the program code.
  4. Blocked state (Blocked): the blocking state is a thread that gives up CPU usage for some reason and stops running temporarily. The thread does not enter the running state until the thread enters the ready state. There are three kinds of
  • Waiting for blocking: the running thread executes the wait () method, and JVM puts the thread in the waiting pool.
  • Synchronous blocking: when the running thread gets the synchronization lock of the object, if the synchronization lock is occupied by another thread, JVM will put the thread into the lock pool.
  • Other blocking: when the running thread executes the sleep () or join () method, or when the I/O request is sent, JVM will put the thread into a blocking state. When the sleep () state is timed out, join () waits for the thread to terminate or timeout, or the I/O is processed, the thread is returned to the ready state.
  1. Dead state (Dead): the thread is finished, or the run () method is exited because of the exception. The thread ends the life cycle.

Java threads: creating and starting

There are two ways to implement multithreading in Java, one is to continue the Thread class, and the other is to implement the Runable interface.

  1. Extended java.lang.Thread class. There is a run in this class () method, should pay attention to its usage:
    public void run (
    ) if the Runnable thread is running object structure independent, then call the Runnable object’s run method; otherwise, the method does not perform any operation and return. The subclass of Thread should override this method.
  2. Implementation of java.lang.Runnable interface. When
    public void run ()
    creates a thread using the object that implements the interface Runnable, starting the thread will result in calling the run method of the object in the thread that is executed independently. The conventional protocol of method run is that it may perform any required operations.

Special note: when the thread is created, the excellent coding proposal, specify the name of the thread, in the dump thread, this will not be the Thread-1, but the thread name of its own.

The start thread calls the start () method on the Thread object of the thread, not the run () or any other method.

thread priority

Each Java thread has a priority, which helps the operating system determine the scheduling order of threads. The priority of the
Java thread is an integer with a value range of 1 (Thread.MIN_PRIORITY) – 10 (Thread.MAX_PRIORITY).
by default, each thread assigns a priority NORM_PRIORITY (5).
threads with higher priority are more important to programs, and processor resources should be allocated prior to low priority threads. However, thread priority does not guarantee the order of thread execution, and it relies heavily on the platform.

Java thread commonly used methods detailed

1. sleep ()

The current thread (called the thread of this method) is paused for a period of time, allowing other threads to continue executing, but it does not release the object lock. That is, if synchronized synchronization is fast, other threads can still not access shared data. Notice that this method catches exceptions.

For example, a simultaneous execution of two thread (no synchronized) a thread priority for MAX_PRIORITY, another is MIN_PRIORITY, if there is no Sleep () method, only a high priority thread after the execution is completed, the lower priority thread to execute; but the high priority thread sleep (500), there is a low priority the opportunity to perform. In short, sleep () can enable low priority threads to be executed, and, of course, allow threads with the same priority and high priority to have execution opportunities.

2. join ()

The join () method makes the thread that calls the method execute before then, and then waits until the thread of the method is executed and continues down. Note that the method also needs to catch exceptions.

3. yield ()

This method is similar to sleep (), but cannot be specified by the user for a long time, and the yield () method only allows threads with the same priority to have execution opportunities.

4. interrupt ()

If the current thread does not interrupt itself (which is allowed in any case), the thread’s checkAccess method is called, which may throw the SecurityException. If the thread in the call to Object class wait (), wait (long) or wait (long, int), or the join (join), (long), join (long, int), sleep (long) or sleep (long, int) blocked the methods in the course of the interrupt status to be clear, it will also receive a InterruptedException. If the thread is blocked in the I/O operation on the interruptible channel, the channel will be closed, the thread’s interrupt state will be set, and the thread will receive a ClosedByInterruptException. If the thread is blocked in a Selector, the interrupt status of this thread will be set, it will immediately return from the selection operation, and may have a non-zero value, it calls the wakeup method as the selector. If the previous conditions are not saved, the interrupt state of the thread will be set. Interrupting a thread that is not active does not require any action.

5. interrupted ()

Test whether the current thread has been interrupted. The interrupt state of the thread is cleared by this method. In other words, if two consecutive calls this method, the second call will return (after false, has cleared the interrupt status on the first call and a second call to test the interrupt status before the end, the current thread is interrupted once again except in the case). Thread interrupts are ignored because the thread that is not active at the time of the interrupt is reflected by the method of returning false from the thread.

A thread before the normal end, forced termination is a very dangerous thing. Because of its serious consequences may be completely unexpected. So you see the Thread.suspend, Thread.stop and other methods are Deprecated.
cannot be directly to a thread to hang up, but sometimes it is necessary to make a thread to die, or let it end a wait state to do? Is an elegant method for the thread of an interrupt signal to let it decide what to do. For example, in a child thread in order to wait for the arrival of some specific conditions, you call the Thread.sleep (10000), 10 seconds after expected thread to sleep wake up yourself, but if the specific conditions ahead of the arrival of the words, how do you notice a sleeping thread? For example, the main thread by calling the join method of sub thread blocking yourself to wait for the child the end of the thread, but during the operation of Zi Xiancheng found himself unable to end in a short period of time, so it needs to tell the main thread don’t wait for me. In these cases, you need to interrupt. The interruption is by calling the Thread.interrupt () method to do. This method by modifying the interrupted state of the calling thread to inform the thread, said it was interrupted. For non blocking the thread, just change the interrupt status, namely (Thread.isInterrupted) will return to true; in the blocking state can be cancelled for example, waiting in the thread, these functions on Thread.sleep (Object.wait), thread (), Thread.join (), this thread receives the interrupt signal, InterruptedException will be thrown, and put the interrupt status back to false.

//Interrupted classic void run use the code public () {try{... While. (Thread.currentThread).IsInterrupted ((!) & & more work to; do) {/ / do more work;}}catch (InterruptedException e thread was interrupted during) {/ / sleep / / or wait finally{cleanup if required}}},

Obviously, in the code above, one of the determinants of the while loop is the need to constantly check its own interrupt state. When the external thread calls the interrupt of the thread, the interrupt state is changed to true. This is the do more work that the thread will terminate the loop and is not executing the loop. This shows that interrupt interrupts a part of the thread’s business logic, on the premise that the thread needs to check its own interrupt state (isInterrupted ()). But when threads are blocked, for example, blocked by one of three ways of Object.wait, Thread.join, and Thread.sleep. Call its interrput () method. One can imagine that it is impossible to set up the interrupt state without threading the CPU running. This generates an InterruptedException exception.

* * if the thread is blocked, it can't check the shared variables, it cannot stop. This happens in many cases, for example, when calling * Object.wait (), ServerSocket.accept () and DatagramSocket.receive (), they may always block the thread for a long time. Even if a timeout occurs, it is not feasible and inappropriate to wait until the timeout is complete, so let the thread get out of the blocked state earlier with some mechanism. Unfortunately, there is no such mechanism that applies to all situations, but, depending on the situation, specific technologies can be used. Using the Thread.interrupt () interrupt thread *, as described in Example1, the Thread.interrupt () method does not interrupt a running thread. What this method actually does is throw an interrupt signal when the thread is blocked so that the thread exits the blocking state. * more precisely, if the thread is one of Object.wait, Thread.join and Thread.sleep three methods of blocking, then, * it receives an interrupt exception (InterruptedException), and early end blocked state. Therefore, if the thread is blocked by the above methods, the correct thread stopping method is to set the shared variable and call interrupt (). If the thread is not blocked, then calling interrupt () will not work; otherwise, the thread will get an exception (the thread must be prepared beforehand to benefit the situation), and then escape from the blocking state. In any case, the most posterior thread checks the shared variable and then stops. The following example describes this technique. * * / package Concurrency.Interrupt; class Example3 extends Thread volatile Boolean {stop = false; public static void main (String args[]) throws Exception thread new Example3 {Example3 = (); System.out.println ("Starting thread..."); (thread.start); Thread.sleep (3000); System.out.println ("Asking thread to stop..."); * * if the thread is blocked, will not check this variable, after the call to interrupt, thread can as soon as possible end resistance * plug, can check this variable. * * / * * / thread.stop = true; this method is actually completed, an interrupt signal in the thread is blocked, it will be a thread blocking back * * / thread.interrupt * (state); Thread.sleep (3000); System.out.println ("Stopping application..."); System.exit (0);} public void (run) {while (! Stop) {System.out.println ("Thread running..."); try {Thread.sleep} (2000); catch (InterruptedException E) {/ / receives an interrupt exception (InterruptedException), and early end blocked state System.out.println ("Thread interrupted...");}} System.out.println ("Thread exiting unde R request... ");}} / * * to grasp the key points: stop variables, run method in sleep (interrupt), (InterruptedException). Bridge * is this meaning: when we call the run method (sleep method or other blocking threads), if the thread is blocked * long time, such as 10s, in the 10s, thread blocking, run method is not executed, but if in this 10s, stop is a * the true shows that the termination of this thread, but now the thread is blocked, not its run method, naturally * can not check the stop, so the thread cannot be terminated, this time, we can use the interrupt () method: we * thread.stop = true; thread.interrupt statement (call) method, this method will throw an interrupt signal in * thread is blocked, the signal will be captured by the catch statement, once captured this signal, the thread is ahead of the end of their own The blocking state, this *, it can run again run method, then check to stop = true, while cycle will no longer be executed after the execution, the * while behind the cleanup work, the run method is executed, the thread terminates. * * /

When you want to throw a InterruptedException in the code call, you can choose to reset the interrupt state, or you can choose to throw out the InterruptedException, which is determined by the caller in the outer layer.
not all received after the interruption blocking method can cancel the blocking state, input and output stream class will block and wait for I/O to finish, but they do not throw the InterruptedException, but also will be interrupted in the case out of the blocking state.
attempts to obtain an internal lock operation (entering a synchronized block) that cannot be interrupted.

The synchronous operation of the thread will be explained in detail in the following chapters.

Individual public number

System learning java high concurrency series two
ingenuity zero public number.Jpg