JAVA multithreading and concurrency knowledge point summary, java Multithreading

Source: Internet
Author: User

JAVA multithreading and concurrency knowledge point summary, java Multithreading
Reprinted please indicate the source: http://blog.csdn.net/zhoubin1992/article/details/46861397

Last time I summarized a summary of JAVA object-oriented and collection knowledge points:
Http://blog.csdn.net/zhoubin1992/article/details/46481759
Inspired by bloggers, this time I will summarize JAVA multi-thread and concurrency knowledge points to help you learn and use them for your own review.

1. What are processes and threads? What is the difference between a thread and a process?

1. Process
When a program runs in the memory, it becomes a process. A process is a running program.
A process is an independent unit for the operating system to allocate and schedule resources.
Three features of a process:

  • Independence
    An independent entity. Each process has its own private memory space.
  • Dynamic
    A program is a set of static commands, and a process is a set of commands that are active in the system.
  • Concurrency
    Multiple processes can be concurrently executed on a single processor.
Concurrency and concurrency means that only one command can be executed at a time point, but multiple process commands are quickly rotated, so that multiple processes can be executed simultaneously at a macro level. Parallelism refers to the simultaneous execution of multiple commands on multiple processors at the same time point.

2. threads
A thread is the smallest unit that the operating system can schedule operations. It is included in the process and is the actual operating unit of the process. A thread is also called a lightweight process. Threads are independent and concurrent execution streams in the process.
3. Differences between threads and processes

Ii. Advantages of Multithreading 3. Thread creation method in Java

1. inherit the Thread class to create a Thread class

4. Comparison between Runnable, ThreadJava, and thread creation methods?

In java multithreading, it is generally recommended to use the Runnable interface to create multithreading, because implementing the Runnable interface has the following advantages and disadvantages compared to inheriting the Thread class:

  • To implement the Runnable interface, the Thread class only implements the interface and can inherit other classes. If it inherits the Thread class, it cannot inherit other parent classes.
  • To implement the Runnable interface, multiple threads can share the same target object, so it is suitable for multiple thread zones with the same program code to process the same resource. Separation of data and Code reflects the idea of object-oriented.
  • To implement the Runnable interface and access the current Thread, you must use the Thread. currentThread () method. If you inherit the Thread class, use this to get the current Thread.
    It is complementary to http://blog.csdn.net/ns_code/article/details/17161237.
5. What are the differences between the start () and run () methods in the Thread class? 6. Thread Lifecycle

Five States of Java threads:

  • Dead): After the run () method of the thread is executed, or the run () method is exited due to an exception, the thread ends its life cycle.
    When the main thread ends, other threads are not affected.
  • 7. java thread control method

    1. join thread
    The join method is called by A thread object. If the join method of another thread B is called in thread A, thread A will wait until thread B completes execution.
    2. Daemon Thread)
    Java has two types of threads: User Thread and Daemon Thread ).
    The user thread is the thread running on the foreground, while the daemon thread is the thread running on the background. The daemon thread is used to facilitate the running of other foreground threads. It is only required when normal and non-daemon threads are still running. For example, the garbage collection thread is a daemon thread. When there is only one daemon thread left in the VM detection and all user threads have exited, the VM will quit because no daemon is required, there is no need to continue running the program. If a non-daemon thread is still alive, the VM will not exit.
    Daemon features: If all foreground threads die, background threads automatically die.
    The daemon thread is not provided only within the virtual machine. You can also set the daemon thread when writing a program. You can use the setDaemon (true) method of Thread to set the current Thread as the daemon Thread.
    Although the daemon thread may be very useful, you must be careful to ensure that all other non-daemon threads will not cause any harm due to its termination. It is impossible for you to know whether the daemon thread has completed the expected service task before all user threads exit. Once all user threads exit, the virtual machine exits. Therefore, do not perform business logic operations (such as data reading and writing) in the daemon thread ).
    Note the following points:

    1. setDaemon (true) must be set before the start () method of the thread is called; otherwise, an IllegalThreadStateException occurs. 2. The new thread generated in the daemon thread is also the daemon thread. 3. Do not think that all applications can be allocated to the daemon for service, such as read/write operations or computing logic.

    Reference http://blog.csdn.net/ns_code/article/details/17099981
    3. Thread concession (yield)
    Yield can be called directly using the Thread class, so that the currently executing Thread can be paused without blocking the Thread, but the Thread is transferred to the ready state. Yield gives the CPU execution right to threads of the same level. If there are no threads of the same level waiting for the execution right of the CPU, the thread continues to execute.

    VIII. Differences between sleep () and yield () Methods 9. Why are the sleep () and yield () Methods of the Thread class static?

    The sleep () and yield () Methods of the Thread class will run on the Thread currently being executed. Therefore, it is meaningless to call these methods on other threads in the waiting state. They can work in the currently being executed thread and prevent programmers from mistakenly believing that they can call these methods in other non-running threads.
    Currently, only the current thread can be sleep. the current thread is voluntary. make sleep () an instance method. The current thread can sleep other threads directly, which introduces many multithreading problems, such as deadlocks.
    Destroy (), suspend (), stop (), and resume () are all deprecated (deprecated) instance methods ). What survived? Only static methods (only operations on the current thread and some mild instance methods, such as getXXX (), isXXX (), join (), and yield.

    10. What is the difference between sleep and wait? 11. thread security issues

    Thread security issues refer to access to shared resources in a multi-threaded environment, which may cause inconsistency of the shared resources. Therefore, to avoid thread security issues, concurrent access to the shared resources in a multi-threaded environment should be avoided.

    12. synchronous code block

    The format of the synchronous code block is as follows:

     synchronized (obj) {                 //... }

    Obj is the Lock Object. Therefore, it is critical to select an object as the lock. GenerallySelect this shared resource object as the Lock Object.
    At any time, only one thread can lock the Lock Object. Other threads cannot obtain or modify the Lock Object. After the synchronization code block is executed, the thread releases the Lock Object.
    In this way, only one thread in a concurrent thread can enter the code section (critical section) for modifying shared resources at any time, thus ensuring thread security.

    XIII. Synchronization Method

    The synchronized keyword is added to the method definition for accessing shared resources. This method is called a synchronization method. The lock object is the object of the current method. In a multi-threaded environment, when this method is executed, the synchronization lock must be obtained first (and only one thread can obtain the lock at most). Only after the thread executes this synchronization method, will release the Lock Object, other threads will be able to obtain this synchronization lock, and so on...

     public synchronized void a() {             // .... }

    Variable class thread security is at the cost of reducing program running efficiency. To reduce the negative impact of program security, the program can adopt the following policies:
    -Do not synchronize all methods of the thread security class, but only those methods that change the competing resources.
    -If the variable class has two Running Environments: Single-thread and multi-thread environments, two versions should be provided for the variable class: the full version of thread instability and the thread security version. The thread-safe version is used in a single-threaded environment to ensure performance. The thread-safe version is used in a multi-threaded environment.

    14. When will the synchronization monitor be locked?

    The program cannot explicitly release the lock on the synchronization monitor. The thread can release the lock in the following ways:
    A. When the synchronization method of the thread and the execution of the synchronization code library are completed, the synchronization monitor can be released.
    B. When a thread encounters break or return in synchronizing code libraries and methods, it can also release the code.
    C. When a thread encounters an unprocessed Error or Exception in synchronizing code libraries and methods, the synchronization monitor can be released even if the code ends.
    D. When the thread is synchronizing the code library and synchronization method, the program executes the wait Method for synchronizing the monitor object, causing the method to pause and release the synchronization monitor.

    In the following cases, the synchronization monitor will not be released: A. When A Thread is executing A synchronous code library and A synchronous method, the program calls the Thread. sleep ()/Thread. yield () method to pause the current program. The current program will not release the synchronization monitor B. When the thread is executing the synchronization code library and synchronization method, other threads call the suspend method of the thread to suspend the thread. The thread will not release the synchronization monitor. Avoid using suspend and resume whenever possible
    15. Lock)

    Generally, Lock provides more extensive Lock operations than the synchronized Method and the synchronized code block. Lock has a more flexible structure and has a large difference, and supports multiple Condition objects.
    Lock is a tool that controls multiple threads to access shared resources. Generally, a Lock provides exclusive access to shared resources. Only one thread can Lock the Lock object at a time,
    The thread should obtain the Lock Object before accessing shared resources. However, some locks support concurrent access to shared resources, such as ReadWriteLock (read/write lock). In thread security control,
    ReentrantLock (reentrant lock) is usually used ). You can use this Lock object to display the Lock and release the Lock.

    Class C {// lock Object private final ReentrantLock lock = new ReentrantLock ();...... // method to ensure thread security public void method () {// lock. lock (); try {// operation code to ensure thread security} catch () {} finally {lock. unlock (); // release the lock }}}

    When using the Lock Object for synchronization, when locking or releasing the Lock, pay attention to putting the Lock in finally to ensure that it can be executed. The use of locks is similar to the use of synchronization, but the call of the Lock method displayed when the lock is used for synchronization. When synchronized is used, the system uses the current object as the synchronization monitor implicitly. The operation modes are also "lock-> access-> release lock, only one thread can be used to operate resources.
    The synchronous method and the synchronous code block use an implicit synchronization monitor related to competing resources, and force the lock and release lock to appear in a block structure. When multiple locks are obtained, they must be released in reverse order and all resources must be released within the same range as when all locks are obtained.
    Lock provides the synchronization method and other functions not available in the synchronization code library, including the tryLock method used for non-block structure. It has tried to obtain the lockInterruptibly () method, you can also obtain the tryLock (long, timeUnit) method of the timeout lock.
    ReentrantLock is reentrant, that is, the thread can lock the ReentrantLock that has been locked again. The ReentrantLock object will maintain a counter to track nested calls to the lock method. Each time the thread calls lock () after the lock is applied, you must call unlock () to release the lock. Therefore, a protected code can call another method protected by the same lock.

    16. deadlock

    When two threads wait for each other to determine whether to synchronize the monitor, a deadlock occurs. The JVM does not take measures to handle the deadlock. This requires us to handle or avoid the deadlock.
    Once a deadlock occurs, the entire program neither has an exception nor an error or prompt, but the thread will be blocked and cannot continue.
    Thread suspend can easily lead to deadlocks, so we do not recommend using this method to suspend threads in Java.
    For more information, see http://ifeve.com/deadlock.
    Most of the Code is not prone to deadlocks. Deadlocks may hide for a long time in the code, waiting for uncommon conditions to occur, but even if it is a small probability, once a deadlock occurs, this can cause devastating damage. It is difficult to avoid deadlocks,The following principles help avoid deadlocks::

    1. Only hold the lock in the shortest time necessary. Use the synchronous statement block to replace the entire synchronization method. 2. Try to write code that requires multiple locks at different times, if this is unavoidable, make sure that the thread holds the second lock for as short as possible. 3. Create and use a large lock to replace several small locks and use the lock for mutual exclusion, instead of being used as an object-Level Lock for a single object;

    Reference: http://blog.csdn.net/ns_code/article/details/17200937

    I read these books and summarized them by referring to network materials. Next, we will summarize the knowledge about thread communication, thread pool, and thread security set. I will update it in this blog ~

    Refer:
    Http://ifeve.com/java-multi-threading-concurrency-interview-questions-with-answers/
    Http://ifeve.com/java-concurrency-thread-directory/
    Http://www.importnew.com/12773.html
    Http://www.cnblogs.com/lwbqqyumidi/p/3804883.html
    Java programming ideas
    Java crazy handout

    Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

    Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.