The basic method of the thread

The basic thread-related methods wait, notify, notifyAll, sleep, yield, join and so on. The method of controlling operation of a thread, the thread state and affect change.

Thread wait: wait method

Thread calls the wait method will enter WAITING state; only will not return until after the notice of other threads or interrupted. Note that in the call wait method releases the lock of the object , and therefore, the wait method is generally used a method in synchronization blocks or synchronization code.

Thread sleep: sleep method

Call sleep causes the current thread to sleep. Different from the method wait at, sleep method does not release the currently occupied lock, causes the thread into the TIMED-WAITING state; and wait method causes the current thread to enter WAITING state.

Thread concession: yield method

Call the yield method will make the current thread let out (release) CPU execution time slice, slice again competing for CPU time with other threads.

In general, high priority threads are more likely to compete to CPU time slices; but this is not absolute, and some are not sensitive to the OS thread priority.

Thread interrupts: interrup method

interrup method for a thread to issue a notice of termination signal, it will affect an internal interrupt flag of the thread, the thread itself and will not call interrup method change state. Specific changes state to wait for the final identification of the interrupt program processing result received is determined. Understanding of interrup method should pay attention to accept 4 core point:

  • Call interrup method does not interrupt a running thread; thread that is in the Running state and will not be interrupted and terminated only changed the internal maintenance of the interrupt flag, nothing more. The core JDK source code:
    /**
         * Tests whether the current thread has been interrupted.  The
         * <i>interrupted status</i> of the thread is cleared by this method.  In
         * other words, if this method were to be called twice in succession, the
         * second call would return false (unless the current thread were
         * interrupted again, after the first call had cleared its interrupted
         * status and before the second call had examined it).
         *
         * <p>A thread interruption ignored because a thread was not alive
         * at the time of the interrupt will be reflected by this method
         * returning false.
         *
         * @return  <code>true</code> if the current thread has been interrupted;
         *          <code>false</code> otherwise.
         * @see #isInterrupted()
         * @revised 6.0
         */
        public static boolean interrupted() {
            return currentThread().isInterrupted(true);
        }
    
        /**
         * Tests whether this thread has been interrupted.  The <i>interrupted
         * status</i> of the thread is unaffected by this method.
         *
         * <p>A thread interruption ignored because a thread was not alive
         * at the time of the interrupt will be reflected by this method
         * returning false.
         *
         * @return  <code>true</code> if this thread has been interrupted;
         *          <code>false</code> otherwise.
         * @see     #interrupted()
         * @revised 6.0
         */
        public boolean isInterrupted() {
            return isInterrupted(false);
        }

     

  • Ruoyin call sleep method the thread is in TIMED-WAITING state, calling interrupt method throws InterruptedException, ahead of the end of the thread TIMED-WAITING state.
  • Many methods that throw InterruptedException, such as Thread.sleep (long mills), an exception is thrown in front will clear the interrupt flag, so called after throwing an exception interrupted method will return false.
  • Thread interrupt status is inherent in a flag, this flag can terminate the security thread. For example, when you want to terminate a thread, you can call interrupt method of this thread, then the thread's run method returns the status value of the security thread according to terminate the thread isInterrupted method.
    public class SafeInterruptThread extends Thread {
        @Override
        public  void run(){
            if(!Thread.currentThread().isInterrupted()){
                try {
                    //☆此处处理正常的线程业务逻辑
    
                    //sleep会抛出InterruptedException
                    sleep(11);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); //重置中断标识
    //                e.printStackTrace();
                }
            }
            if(Thread.currentThread().isInterrupted()){
                //☆处理线程结束前必要的一些资源释放和清理工作。比如释放锁。
                //存储数据到持久化层、发出异常通知等,用于実現线程的安全退出。
                try {
                    sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    //☆ 定义一个可安分退出的线程
    SafeInterruptThread thread = new SafeInterruptThread();
    //☆ 安全退出线程
    thread.interrupt();

     

Thread adding: join method

join method for waiting for the other thread to terminate; if join method calls another thread in the current thread, the current thread into the blocked state, until the end of another thread, the current thread is then blocked by the state to the ready state, waiting to acquire the CPU use rights. In many cases, the main thread to create and start a child thread needs to wait until the child thread and return the results collected and processed and then quit, then we should use the join method. Specific methods are as follows:

ChildrenThread childrenThread = new ChildrenThread();   //子线程开始运行
childrenThread.join();                                  //等待子线程childrenThread执行结束
//子线程join()结束,开始运行主线程

Thread wakes: notify method

Object class has the notify method for waking up a thread waiting on this object's monitor. If all threads are waiting on this object will be selected wake up one thread. Choice is arbitrary.

We usually call one of the objects of the wait method on an object's monitor wait until the lock on this object for the current thread to give up, to continue to be awakened thread, the thread will be woken up in a conventional manner and actively synchronized on that object the other thread competition.

Similar methods also notifyAll, used to wake up all threads waiting on the monitor.

Daemon thread: setDaemon

setDaemon method for defining a daemon thread, also known as "service thread", the thread is a background thread, it has a feature that provides a public service for the user thread will automatically leave when no user serviceable thread.

Guardian lower priority thread, is used to provide services to other objects and threads in the system. Will set a user thread as a daemon thread method is to create a thread object before the thread object setDaemon (true) to set.

Thread defined in the daemon thread is daemon thread. Daemon thread is the JVM level, such as GC thread is a typical daemon thread in our program, there is no longer any thread running, the program will not produce garbage, the garbage collector there is nothing to do, so on the recovery of the JVM remaining threads, GC thread will leave automatically. It is always run at a low level state, recyclable resources for real-time monitoring and management systems.

Daemon thread is a special thread running in the background, independent of the control terminal, and periodically perform some task or pending some event has occurred. That daemon thread is not dependent on the terminal, but depends on the JVM, the JVM with the total death. When all threads in the JVM are daemon threads, JVM can quit. If there is non-daemon thread, the JVM will not quit.

Impact of each method on the thread state

The difference between sleep and wait method of method

The method of the Thread class belongs to sleep; and wait method belong to the class Object

sleep method to suspend the specified time, so that the CPU to other threads, but it remains to monitor state, the state will automatically resume operation after a specified time.

In the method of procedure calls sleep, the thread will not release the object lock.

When you call the wait method, the thread will give up the object lock, waiting to enter the pool waiting for the lock for this object, calling only for this object notify the method, the thread pool ready to enter the object lock acquire the object lock, and enter the running state.

start & run

  • start method for starting the thread; Mika now truly multi-threaded operation. After calling the start, the thread will execute in the background, without waiting for the run method body code execution is completed, you can continue with the following code.
  • When you call start start a thread, the thread is in the ready state and is not running.
  • run method, also known as the thread body. After calling the run, the thread into the running state. Thread terminates after the run.

Terminate the thread of the four ways

1. finishes running normally

Body thread execution is completed.

2. Use the exit sign exit thread

Under normal circumstances, when the run method been executed, the thread will be the normal end. However, some thread is a background thread, you need to run a long time, after only meet certain specific conditions in the system, in order to trigger a shutdown. Then you can use a variable to control, and true or false to control it by setting this flag.

Example:

public class ThreadSafe extends Thread {
    public volatile boolean exit = false;
    @Override
    public void run(){
        while (!exit){
            //业务逻辑代码
        }
    }
}

The above code defines a quit exit sign in the thread, its default value is false. Used to define the exit of a Java keyword volatile , this keyword is used to exit the security thread synchronization, which means that at the same time only one thread can modify the exit value. When exit is true, while loop exits.

3. Use the interrupt method terminates the thread

Terminate the thread using the interrupt method has the following two cases:

1) thread is blocked.

For example, when using a sleep, call the lock wait or call the socket of the receiver, accept other methods to make the thread is blocked . When calling interrupt method throws InterruptedException exception. We capture the exception through the code, then break out of the loop detection state, you have the opportunity to end the execution of this thread. Note that not just call the method to interrupt the thread ends , it must first capture InterruptedException anomaly and then break out of the cycle to the end of the normal run method.

Implementation:

public class ThreadSafe extends Thread {
    @Override
    public void run() {
        while (!isInterrupted()) {   //在非阻塞过程中通过判断中断标志来退出
            try {
                Thread.sleep(5 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;              //在捕获到异常后执行break跳出循环
            }
        }
    }
}

2) thread is not blocked state

This time using the method for determining the interrupt flag isInterrupted thread to exit the loop. When calling interrupt method, the interrupt flag is set to true, and the thread can not exit immediately , but resource release operation before execution thread terminates, the thread is waiting to exit after resource release is completed.

4. Use the stop method to terminate threads: unsafe

In the program can call the method directly Thread.stop forced to terminate the thread, but this is very dangerous, could have unpredictable consequences.

It's like suddenly powered off.

When the program uses Thread.stop method to terminate the thread, the child thread the thread will throw ThreadDeathError error, and release all child threads holding the lock . Locked block of code is generally used to protect data consistency, if the lead held by the thread after calling the method Thread.stop sudden release all the locks so that the lock can not control the resources, the protection of data may appear inconsistent with the Happening.

 

Published 28 original articles · won praise 3 · Views 5294

Guess you like

Origin blog.csdn.net/u012632105/article/details/104689923