Java Concurrent Programming Fundamentals

What is thread:

       The smallest unit of operating system operation scheduling, a lightweight process, a thread contains independent counters, stacks, local variables and other attributes, and the heap memory can be shared between threads. The so-called multi-threaded program, that is, the processor allocates time slices to different threads through context switching, which makes people feel that the threads are executed at the same time.

Why use multithreading:

  • Make full use of multi-core processors
           , there will be multiple threads under one process, and the operation of one thread will occupy one processor core. Now that multi-core CPUs are commonplace, if we are still programming single-threaded, only one core in multi-core CPUs will be used, and the other cores will be idle. In order to reuse the CPU multi-core resources and improve the computing power, we use multi-threading, which can run multiple threads on the multi-core CPU at the same time.

  • Faster responsive experience

           For example, if we request a page, if it is a single thread, it will get the video, pictures, text and other resources on this page one by one; if it is multi-threaded, it will send back the resources on this page to shorten the page loading time. Faster speed, better user experience.

Thread priority:

       The number of time slices allocated by a thread also determines how much processor resources the thread uses, and the thread priority is the thread attribute that determines whether the thread needs to allocate more or less processor resources.

Status of the thread:

  • NEW: The thread has been constructed, but has not yet started running (thread.start() has not been executed);

  • RUNNABLE: The readiness of the thread and the running of the thread are both called the RUNNABLE state;

  • BLOCKED: Blocked state. When a thread waits to acquire a lock held by another thread through Synchronized, it presents the BLOCKED state

  • WAIT: waiting state; Lock lock blocking; object.wait();Thread.join();LockSupport.part() state presented

  • TIME_WAITING: A method with a timeout limit usually presents the TIME_WAITING state after execution. It is equivalent to adding a supermarket limit on the basis of the WAIT state. For example, Thread.Sleep(long n);;Thread.join(long n)

  • TERMINATE: the status of the thread termination

Daemon thread:

       Daemon thread is a kind of support thread, which is mainly used for background scheduling and support work in the program. When there are no non-daemon threads in a Java virtual machine, the Java virtual machine will exit.

       Note : There is no guarantee that the finally block in the Demon thread will execute.

The construction of the thread:

       The construction of threads is also the initial process. Usually a thread is created by its parent process: the parent process allocates space for the child process, the child process inherits InheritableThreadLocal, inherits classLoader, inherits whether Demon, and the child process obtains a unique ID

Thread interruption:

A flag attribute of a thread that indicates whether a running thread has been interrupted by other threads.

isIntrrupted() method: determine whether it is interrupted;

Thread.interrupted(): Reset the interrupt flag bit of the current thread;

  • If the thread is already in the terminal state, even if the thread has been interrupted, the isInterrupted() method of the thread object returns false;
  • Declare the method that throws InterruptedException. Before throwing the exception, the java virtual machine first clears the interrupt flag, and calls the isInterrupted method to return false;

Terminate the thread safely:

  • through the interrupt flag;
  • via boolean variable;

Communication between threads:

  • Volatile: used to modify fields (member variables), to inform the program that any access to the variable needs to be obtained from shared memory, and changes to it must be refreshed back to shared memory synchronously to ensure the visibility of variable access by all threads;
  • synchronize: Modified method or synchronization is fast; ensures that multiple threads can only have one thread in the method or synchronization fast at the same time, ensuring the visibility and exclusivity of thread access to variables;
  • Waiting/notifying mechanism: One thread modifies the value of an object, while another thread perceives the change and operates, the former is a producer and the latter is a consumer.

Existing problems:

  • Difficult to ensure timeliness: During sleep, processor resources are basically not consumed, but if you sleep for too long, you cannot find out that conditions have changed in time;
  • Difficult to reduce overhead: reducing sleep time may consume more processor resources;

Solution: wait/notify mechanism;

  • notify(): notify a thread waiting on the object to return from the wait() method, and the condition of the return is that the thread acquires the lock of the object;
  • notifyAll(): notify all locks waiting on this object;
  • wait(): The thread calling this method enters the WAITING state, and will return only after waiting for notification from another thread or being interrupted. After calling the wait() method, the lock of the object will be released;
  • wait (long): wait for a period of time overtime, the parameter is milliseconds, and it will return overtime without notification;
  • wait(long, int): More fine-grained control of the timeout, which can reach nanoseconds;

Classic paradigm of await (consumer)/notify (producer):

        Waiting party principle :

  • acquire the lock of the object;
  • If the condition is not met, call the wait method of the object, and still check the condition after being notified;
  • If the conditions are met, the corresponding logic is executed;

Fake code:

         synchronized(object)

                {

                        while (condition not satisfied)

                                  {

                                                object.wait();

                                     }

                          Corresponding processing logic;

            }

            Notifying Party Principles :

  • acquire the lock of the object;
  • changing conditions;
  • Notify all threads waiting on the object;

Fake code:

            synchronized(object) {

                    change the conditions

                    object.notifyAll();

}

Guess you like

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