java concurrent programming

Basic knowledge

       The essence of a thread is the path of machine execution, and it is the smallest execution unit of the operating system. It is a virtual concept on top of a multitasking operating system. From a hardware perspective, each cup has only one execution path. Hundreds or thousands of threads executing simultaneously is an illusion of operating system scheduling.

 

        Every computer program, or every process, has at least one thread, which is called the main thread, and the main thread of Java is called the main thread. It starts with the main method of a class. Any computer program is started by a single thread. The process has an exclusive memory space, the threads in the process share this memory space, and each thread has a separate stack to store data.

 

terminology of concurrent programming

        Barrier: The barrier represents the rendezvous point of multiple threads. All threads need to reach the rendezvous point before continuing to execute, so the thread that arrives first will enter the wait.

        Condition Variable: A condition variable is a variable associated with a lock (Lock), which is usually used in a synchronous environment to implement a wait-wake mechanism. A thread can wait for a condition variable while holding a lock; or wake up one or all threads waiting for a condition variable while holding a lock.

        Condition variables are also event variables.

        Critical Section: Represents a synchronized method and block of code. All threads must pass through the critical section serially. Essentially a hidden lock acquisition and release area.

         Lock (Lock): used to indicate the access rights of a specific thread entering a critical region. Read/Write Lock (Read/Write Lock) can allow multiple threads to acquire at the same time, as long as they agree to perform "read" operations.

         Monitor: This term has different meanings in different systems, it may refer to Lock, or it may refer to wait-wake mechanism

        Mutex: Similar to Lock, it is often cross-process and based on the operating system level.

        Semaphore: A count of one or more signals that a thread can wait for, and a count of one or more signals that another thread can release. When the thread is alive enough, it stops waiting.

 

 Java thread creation and management

 create thread

 Java allows two styles of creating threads

  1.   Inherit the java.lang.Thread class and override the run method
  2.   Implement the java.lang.Runable interface and pass it to the Thread constructor.

The Thread object does not essentially represent the thread itself, but a package of a set of thread-related methods and data.

The constructor of Thread has the following parameters:

       name : The name of the Thread, the default Thread-N, N is a unique number;

       Runable target : The list of instructions executed by the new thread, located in the run() method

       ThreadGroup group: The thread group that the new thread joins, the default is the same as the thread group of the thread that calls the new thread constructor

       long stackSize: The stack size for storing temporary variables when the new thread executes the method.

 Thread lifecycle methods

        new Thread(): Create a thread. In Java, a thread is also an object, so its object is completed by calling the constructor. A thread exists as soon as it is constructed, but it is not yet executing, where other threads can interact with the thread, such as setting priorities, thread guards, and names.

       start(): Start the thread. After calling the start() method, a new thread is created in the jvm, and the thread's isAlive()==true, waiting for the system to schedule for execution.

      stop(): Terminate the thread. You cannot call the stop() method to terminate the thread. It is defective and has been deprecated.

      sleep()/wait()/join()/suspend(): The thread waits. The suspend() method is used to suspend the thread, but it is as flawed as stop() and has been deprecated. The Thread.sleep() static method allows the thread to suspend for a period of time, and then automatically resume execution. The lock will not be released when sleep is suspended. The Object.wait() method relies on synchronization and cannot be used alone. The wait method releases the lock held by the object.

      notify()/notifyAll()/resume(): The thread resumes, notify() and notifyAll() are used to wake up the thread blocked by calling the wait() method. After the thread is woken up, it will try to get the monitor. resume() is used to resume a suspended thread, which is flawed.

     Clear: After the thread ends, its Java object can be accessed and can be attached with some valuable information. If a Thread thread goes out of scope, it will be reclaimed by the GC, which may result in a cleanup of system resources.

 

 Correct way to stop a thread

set flag bit

 

public class MyThread implements Runnable {

    private volatile boolean flag = true;
    @Override
    public void run() {
        while ( flag )
            ;
        System.out.println( "Thread Interrupt" );
    }

    public static final void main( String[] arg ) throws Exception {
        MyThread myThread = new MyThread();
        Thread thread = new Thread( myThread );
        thread.start();
        System.out.println( "123" );
        TimeUnit.SECONDS.sleep( 5 );
        myThread.setFlag( false );
    }

    public void setFlag( boolean flag ) {
        this.flag = flag;
    }

    public boolean isFlag() {
        return flag;
    }
}
 Take advantage of interrupts

 

 Calling this method gives any thread that is blocking (Blocking) method calls a chance to exit. This method has two effects:

  1. The thread's blocking method (may) throw an InterruptedException, which the program code can catch and exit
  2. Set the thread's internal "interrupted" flag to true, indicating that the thread has been interrupted. This token can be checked using the isInterrupted() method. This flag will be set even if the thread is not blocked
Thread t = new Thread() {
            public void run()
            {
                while ( !isInterrupted() )
                    ;
                System.out.println( "interrupted" );
            }
        };
        t.start();
        TimeUnit.SECONDS.sleep( 1 );
        t.interrupt();

 Use exception judgment (for threads in a blocked state)

Thread t = new Thread() {
            public void run()
            {
                try
                {
                    TimeUnit.SECONDS.sleep( 3600 );
                }
                catch ( InterruptedException e )
                {
                    System.out.println( "interrupted" );
                }
            }
        };
        t.start();
        TimeUnit.SECONDS.sleep( 1 );
        t.interrupt();

    Regarding the interrupt() method, it is also necessary to note:

  1. If the thread is interrupted by other threads when calling the Object.wait(), join(), sleep() methods, its interrupt flag bit will be cleared and an InterruptedException will be received
  2. If a thread is interrupted by another thread while performing I/O on an InterruptibleChannel, the channel is closed, the thread's interrupt flag bit is set, and a ClosedByInterruptException is received. ServerSocketChannel, SocketChannel, FileChannel, DatagramChannel, etc. are all interruptible channels
  3. If the thread is interrupted while performing a select operation on the Selector, the thread's interrupt flag bit is set and returns immediately
 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326211385&siteId=291194637