Thread head figure

Thread related

To create a thread:
1. Transmit the Runnable mode. Thread subclass 3. FutureTask mode.Copy the code
  1. A Runnable way:

The Runnable mode returns no value.

/ * * *@author jtl
 * @date2019/10/11 17:03 * Thread can be created in the following three modes: Runnable */
public class ThreadDemo {
    public static void main(String[] args) {
        //Runnable
        Thread threadA=new Thread(new Runnable() {
            @Override
            public void run(a) {
                System.out.println("Thread is created with runnable"); }},"ThreadA"); threadA.start(); }}Copy the code
  1. Thread subclass method:
/ * * *@author jtl
 * @date2019/10/11 17:03 * Thread can be created in the following three ways: Thread subclass */

public class ThreadDemo {
    public static void main(String[] args) {
        ThreadC threadC=new ThreadC();
        threadC.setName("ThreadC");
        threadC.start();
    }

    private static class ThreadC extends Thread{
        @Override
        public void run(a) {
            super.run();
             System.out.println("ThreadC name is: "+getName()); }}}Copy the code
  1. FutureTask way:

FutureTask: Has a return value. When executing the futureTask.get() method. Blocks the current thread and does not wake it up until the child thread of futureTask completes execution.

/ * * *@author jtl
 * @date2019/10/11 17:03 * Thread can be created in three common ways: FutureTask */

public class ThreadDemo {
    public static void main(String[] args) {
        //FutureTask callable
        Callable<String> callable=new Callable<String>() {
            @Override
            public String call(a) throws Exception {
                Thread.sleep(1000);
                return "Thread is created with callable"; }}; FutureTask<String> futureTask=new FutureTask<>(callable);
        Thread threadB=new Thread(futureTask,"ThreadB");
        threadB.start();
        try {
            long tt=System.currentTimeMillis();
            String msg=futureTask.get();
            Futuretask.get () blocks the main thread until the child thread finishes executing
            // So the elapsed time is 1000+ms
            System.out.println(msg+"-" +(System.currentTimeMillis()-tt));
        } catch(InterruptedException | ExecutionException e) { e.printStackTrace(); }}}Copy the code
Thread life cycle:
1. New (New) : Call the New method to create a thread that is New in its life cycle. At this point, the main task is to allocate memory for the thread and initialize its member variables. 2. Runnable: Call start to start a thread. At this point, the JVM completes the creation of the stack and program counters and waits for the thread to schedule and run. 3. Running: When the Runnable thread is allocated to the CPU time slice, it starts to execute the run method and is in the Running state. The run state is primarily the execution of the code logic in the run method. 4. Blocked: A running thread that actively or passively gives up access to its CPU and is suspended. Thread.sleep(), thread.join (), thread.sleep (), thread.join (), thread.sleep () Dead: A thread terminates or exits due to an exception.Copy the code
There are six states of a thread:
1. NEW: The state of the thread before it is started. 2. RUNNABLE: Indicates the status of the thread when the JAVA VM is running. 3. BLOCKED: a thread that is BLOCKED because it is not competing for a lock when running synchronized methods. WAITING: Call object.wait (), thread.join (), locksupport.park () and other non-timeout methods, causing the Thread to be in a WAITING state and need to be woken up by another Thread. 5. TIMED_WAITING: Sleep, Object.wait(long),Thread.join(long), locksupport.parknanos (), locksupport.parkuntil (), etc. The difference between this and WAITING is that. It sets the timeout WAITING time, but WAITING state does not. 6. TERMINATED: State of the thread when it is TERMINATED.Copy the code
   /**
     * A thread state.  A thread can be in one of the following states:
     * <ul>
     * <li>{@link #NEW}<br>
     *     A thread that has not yet started is in this state.
     *     </li>
     * <li>{@link #RUNNABLE}<br>
     *     A thread executing in the Java virtual machine is in this state.
     *     </li>
     * <li>{@link #BLOCKED}<br>
     *     A thread that is blocked waiting for a monitor lock
     *     is in this state.
     *     </li>
     * <li>{@link #WAITING}<br>
     *     A thread that is waiting indefinitely for another thread to
     *     perform a particular action is in this state.
     *     </li>
     * <li>{@link #TIMED_WAITING}<br>
     *     A thread that is waiting for another thread to perform an action
     *     for up to a specified waiting time is in this state.
     *     </li>
     * <li>{@link #TERMINATED}<br>
     *     A thread that has exited is in this state.
     *     </li>
     * </ul>
     *
     * <p>
     * A thread can be in only one state at a given point in time.
     * These states are virtual machine states which do not reflect
     * any operating system thread states.
     *
     * @since   1.5
     * @see #getState
     */
    public enum State {
        /** * Thread state for a thread which has not yet started. */
        NEW,

        /** * Thread state for a runnable thread. A thread in the runnable * state is executing in the Java virtual machine but it may * be waiting for other resources from the operating system * such as processor. */
        RUNNABLE,

        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * is waiting for a specified thread to terminate.
         */
        WAITING,

        /**
         * Thread state for a waiting thread with a specified waiting time.
         * A thread is in the timed waiting state due to calling one of
         * the following methods with a specified positive waiting time:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         */
        TIMED_WAITING,

        /** * Thread state for a terminated thread. * The thread has completed execution. */
        TERMINATED;
    }
Copy the code
Common approach to threads
1. Thread.sleep(): The current Thread sleeps and the TIMED WATING state occurs when the Thread cedes the CPU. If the thread contends for the lock, the lock is not released when the method is executed. After the sleep time, the CPU competition is renewed. 2. Thread.yield() : To yield CPU resources to recompete with other threads for CPU slices. It is possible that the thread will compete for the CPU again after relinquishing the CPU. 3. Thread. HoldLock (Object) : Passes an Object, and returns a bool. Whether the current thread holds the object lock. 4. Join () : The thread currently executing this method is in a WAITING state. Until the thread calling the Join method completes or another thread calls the interrupt method to report InterruptedException. Thread a = new Thread(); a.join(); This works by calling the wait method of thread instance A. Note that A. Gene (5000) simply puts the thread calling the method into a TIMED_WAITING state. Once 5 seconds have passed, the thread executing the modified method will continue to execute. 5. SetDaemon () : Sets this thread as a daemon thread. The JVM does not exit until all user threads exit. The JVM exits and the daemon thread dies. SetPriority () : Sets the priority of the thread. The thread with a higher priority is more likely to be allocated CPU resources first. The priorities of threads are between thread.min_priority (1) and thread.max_priority (10). 1 is the lowest, 10 is the highest. 7. Thread.interrupted() : Returns whether some threads have been interrupted. Also reset the thread interrupt flag bit. IsInterrupted () returns false. 8. IsInterrupted () : Tests whether some thread has been interrupted. 9.Interrupt () : Calling this method immediately reports InterruptedException when a thread enters a blocking wait state. Exit the BLOCKED or WAITING state. If the Thread is not blocked, this method sets the flag bit in the Thread to true, and isInterrupted() returns true.Copy the code
    /**
     * 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()
     * @revised6.0 * /
    public boolean isInterrupted(a) {
        return isInterrupted(false);
    }
    
    
    /** * 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()
     * @revised6.0 * /
    public static boolean interrupted(a) {
        return currentThread().isInterrupted(true);
    }
    
    
    /** * Tests if some Thread has been interrupted. The interrupted state * is reset or not based on the value of ClearInterrupted that is * passed. */
    private native boolean isInterrupted(boolean ClearInterrupted);
    
    /**
     * Interrupts this thread.
     *
     * <p> Unless the current thread is interrupting itself, which is
     * always permitted, the {@link #checkAccess() checkAccess} method
     * of this thread is invoked, which may cause a {@link
     * SecurityException} to be thrown.
     *
     * <p> If this thread is blocked in an invocation of the {@link
     * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
     * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
     * class, or of the {@link #join()}, {@link #join(long)}, {@link
     * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
     * methods of this class, then its interrupt status will be cleared and it
     * will receive an {@link InterruptedException}.
     *
     * <p> If this thread is blocked in an I/O operation upon an {@link
     * java.nio.channels.InterruptibleChannel InterruptibleChannel}
     * then the channel will be closed, the thread's interrupt
     * status will be set, and the thread will receive a {@link
     * java.nio.channels.ClosedByInterruptException}.
     *
     * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
     * then the thread's interrupt status will be set and it will return
     * immediately from the selection operation, possibly with a non-zero
     * value, just as if the selector's {@link
     * java.nio.channels.Selector#wakeup wakeup} method were invoked.
     *
     * <p> If none of the previous conditions hold then this thread's interrupt
     * status will be set. </p>
     *
     * <p> Interrupting a thread that is not alive need not have any effect.
     *
     * @throws  SecurityException
     *          if the current thread cannot modify this thread
     *
     * @revised 6.0
     * @spec JSR-51
     */
    public void interrupt(a) {
        if (this! = Thread.currentThread()) checkAccess();synchronized (blockerLock) {
            Interruptible b = blocker;
            if(b ! =null) {
                interrupt0();           // Just to set the interrupt flag
                b.interrupt(this);
                return;
            }
        }
        interrupt0();
    }
Copy the code
Differences between sleep and Wait methods:
1. Sleep () is the method of Thread. After calling this method, the current Thread sleeps, and the Thread cedes the CPU and enters the TIMED WATING state. This method does not release the lock. 2. Wait () is an Object method. After calling this method, the current thread enters the WAITING state. This method, typically used with synchronized, releases the lock. The notify()/notifyAll() methods are required to wake up.Copy the code
There are several ways to terminate a thread:
1. Complete the logical code. 2. When a thread is blocked, thread.interrupt is called to catch an InterrutedException. 4. Stop method: This method is deprecated and is not recommendedCopy the code
Three methods are different: isInterrupt(), interrupt(), thread.interrupted ()
1. IsInterrupt () : Returns only the flag bit of whether the current thread is interrupted. 2. Thread.interrupted() : Will mark the bit reset. IsInterrupt () returns false. Interrupt() : catches InterruptException when it is blocked. If it is not blocked, the thread flag is set to true.Copy the code

— — — — — — — — — — — — — — — — — — — — — — — — — — — — a non-blocking case three code test — — — — — — — — — — — — — — — — — — — — — — — — — — — —

/** * @author JTL * @date 2020/3/24 10:49 */ ThreadTest {public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Runnable() { @Override public void run() { int count = 0; // The thread interrupt flag bit is false. Execute the while loop while (! Thread.currentThread().isInterrupted()) { try { if (count < 100) { boolean a = Thread.currentThread().isInterrupted(); System.out.println("isInterrupted:" + a + " " + count++); Thread.sleep(50); } else if (count>=100 && count<200){ boolean a = Thread.currentThread().isInterrupted(); // The flag bit is false thread.currentThread ().interrupt(); // Set the flag bit to: true Boolean b = thread.currentThread ().isinterrupted (); Thread.interrupted(); // Flag bit reset. In this case, the flag bit is false. Boolean c = thread.currentThread ().isinterrupted (); System.out.println("isInterrupted:before:" + a + " isInterrupted:after:" + b + " isInterrupted:after:" + c + " " + count++); }else{ boolean a = Thread.currentThread().isInterrupted(); // The flag bit is false thread.currentThread ().interrupt(); // The flag bit is set to true. Boolean b = thread.currentThread ().isinterrupted (); Println ("isInterrupted:before:" + a + "isInterrupted: after:" + b + "" + count++); count = 0; } } catch (InterruptedException e) { e.printStackTrace(); System.out.println("InterruptedException:"+ count + e.getMessage()); break; // exit the loop}}}}); thread.start(); thread.join(); System.out.println("join:" + "interrupted:" + thread.isinterrupted ()); }}Copy the code

— — — — — — — — — — — — — — — — — — — — — — — — — — — — block the execution interrupt methods of the test — — — — — — — — — — — — — — — — — — — — — — — — — — — —

/** * @author JTL * @date 2020/3/24 10:49 */ class ThreadTest {public static void main(String[])  args) throws InterruptedException { Thread thread = new Thread(new Runnable() { @Override public void run() { try { System.out.println(" thread execution: before sleep "); // Thread sleeps for 10 seconds thread. sleep(10000); System.out.println(" thread execution: after sleep "); } catch (InterruptedException e) { e.printStackTrace(); System.out.println(" Thread exception: "+ LLDB etMessage()); }}}); thread.start(); Thread.sleep(1000); Thread.out.println (" thread.isinterrupted () "); Thread The thread is blocked. The flag bit is the default false thread.interrupt(); Thread The thread is blocked. Thread.out.println ("Thread flag bit: "+ thread.isinterrupted ())); / / thread thread. The flag bit is true}}Copy the code