Java _ Multithreading

Source: Internet
Author: User

Multi-threaded threads: an execution process in a process. Difference between a thread and a process: each process requires the operating system to allocate an independent memory address space for it, while all threads in the same process work in the same address space, these threads can share the same memory and system resources. How to Create a thread? There are two ways to create a thread: 1. Expand java. lang. thread class 2. The implementation of the Runnable interface Thread class represents the Thread class. Its two main methods are: run () -- contains the code Start () executed during the Thread runtime () -- used to start a thread only once. The second startup will throw java. lang. illegalThreadExcetpion: state transition between abnormal threads (Display) new State: the thread object created with the new statement is in the new State, at this time it is the same as other java objects, only the memory ready state is allocated in the heap: After a thread is created, other threads call its start () method, and the thread enters the ready state. A thread in this status is located in the runnerpool and waiting for the CPU permission to be used. Running status: the thread in this status occupies the CPU, and the code of the execution program is blocked: When the thread is in the blocking status, the Java virtual machine does not allocate a CPU to the thread until the thread enters the ready state again. The blocking status can be divided into three situations: 1. Blocking status in the object wait pool: When the thread is running, if the wait () method of an object is executed, the Java Virtual Machine places the thread back to the waiting pool of the object. 2. The thread is in the blocking status of the object lock. When the thread is in the running status, it tries to obtain the synchronization lock of an object, if the synchronization lock of this object has been occupied by other threads, JVM will put this thread in the object's wretched pool. 3. Other blocking states: when the current thread executes the sleep () method, or calls the join () method of another thread, or sends an I/O request, it will enter this status. Dead state: When the thread exits the run () method, it enters the dead state, and the thread ends its lifecycle. Or the isAlive () method that Exits normally or encounters an exception to exit the Thread class determines whether a Thread is alive. When the Thread is in the dead or new state, this method returns false, in other States, this method returns true. thread Scheduling Model: time-sharing scheduling model and preemptible scheduling model JVM adopts the preemptible scheduling model. The so-called multi-thread concurrent operation refers to the macro view that each thread obtains the CPU right in turn and executes their respective tasks separately. (Thread scheduling is not cross-platform. It depends not only on the Java virtual machine, but also on the operating system.) If you want to explicitly give another thread a chance to run, one of the following methods can be taken: 1. Adjust the priority of each Thread. 2. Let the running Thread call the Thread. sleep () method 3. Let the running Thread call the Thread. yield () method 4. Let the running Thread call the join () method of another Thread to adjust the priority of each Thread. setPriority (int) and getPriority () of the Thread class () the method is used to set the priority and read priority respectively. If you want the program to be able to move values to various operating systems, make sure that only MAX_PRIORITY, NORM_PRIORITY, and MIN_PRIORITY are used when setting the thread priority. Thread sleep: When the thread executes the sleep () method during running, it will discard the CPU and turn to the blocking state. Thread concession: When the Thread executes the yield () Static Method of the Thread class during running, if other threads with the same priority are in the ready state, then yield () the method puts the currently running thread in the running pool and enables another thread to run. If there are no runnable threads with the same priority, the yield () method does not do anything. The Sleep () method and yield () method are both static methods of the Thread class, which will cause the currently running Thread to discard the CPU and give the running opportunity to other threads. The difference between the two is: 1. The sleep () method will give other threads a chance to run without considering the priority of other threads. Therefore, it will give lower threads a chance to run. yield () the method only gives the thread with the same or higher priority a chance to run. 2. When the thread executes the sleep (long millis) method, it will go to the blocking state. The parameter millis specifies the sleep time. When the thread executes the yield () method, will go to the ready state. 3. The sleep () method declaration throws an InterruptedException exception, while the yield () method does not declare that any exception is thrown. 4. The sleep () method is better than the yield () method () the method has better portability and waits for the end of other threads: the currently running thread of join () can call the join () method of another thread, and the currently running thread will be switched to the blocking state, it does not resume until another thread finishes running. Timer: a Timer class Timer is provided in the java. util package of JDK, which can regularly execute specific tasks. Synchronous atomic operations of threads: According to Java specifications, assignments or return values of basic types are atomic operations. However, the basic data types here do not include long and double, because the JVM sees a basic storage unit of 32 bits, and both long and double are expressed in 64 bits. Therefore, it cannot be completed within one clock cycle. The auto-increment operation (++) is not an atomic operation because it involves one read and one write operation. Atomic operations: a group of related operations may manipulate the resources shared with other threads. To ensure correct calculation results, a thread is executing atomic operations, other measures should be taken to prevent other threads from manipulating shared resources. Synchronous Code block: to ensure that each thread can perform atomic operations normally, Java introduces a synchronization mechanism. Specifically, the synchronized mark is added before the code representing atomic operations, such code is called a synchronization code block. Synchronization lock: each JAVA object has only one synchronization lock. At any time, only one thread can own the lock. When a thread attempts to access a code block with the synchronized (this) Mark, it must obtain the lock of the object referenced by the this keyword. In the following two cases, the thread has different fate. 1. If the lock has been occupied by other threads, JVM will put the thread in the lock pool of the current object. This thread is blocked. There may be many threads in the lock pool. When other threads release the lock, JVM will randomly retrieve a thread from the lock pool so that the thread can have the lock and go to the ready state. 2. If the lock is not occupied by other threads, this thread will get the lock and start to execute the synchronization code block. (In general, the synchronization lock is not released when the synchronization code block is executed, but the object lock is also released in special circumstances. For example, when the synchronization code block is executed, an exception occurs, causing the thread to terminate, the lock is released. When the code block is executed, the wait () method of the object to which the lock belongs is executed. This thread releases the object lock and enters the waiting pool of the object.) features of thread synchronization: 1. If a synchronous code block and a non-synchronous code block operate on shared resources at the same time, it will still cause competition for shared resources. Because when a thread executes the synchronous code block of an object, other threads can still execute the non-synchronous code block of the object. (The so-called synchronization between threads means that when different threads execute the synchronization code block of the same object, they are mutually restrained by obtaining the synchronization lock of the object) 2. Each object has a unique synchronization lock. 3. You can use the synchronized modifier before the static method. 4. When a Thread starts to execute a synchronous code block, it does not mean that it must be run continuously. The Thread that enters the synchronous code block can execute the Thread. sleep () or execute Thread. yield () method. At this time, it does not release the object lock, but only gives the running opportunity to other threads. 5. the Synchronized statement will not be inherited. If a quilt class with the synchronized modifier is overwritten, the method in the subclass will not be synchronized unless it is modified with Synchronized. Thread-safe class: 1. Objects of this class can be securely accessed by multiple threads at the same time. 2. Each thread can normally perform atomic operations and get the correct results. 3. After each thread's atomic operation is complete, the object is in a logical and reasonable state. Release the Lock of an object: 1. After the synchronization code block is executed, the lock of the object will be released. 2. When the synchronization code block is executed, the thread is terminated due to an exception, the lock will also be released. 3. During the execution of the synchronization code block, the wait () method of the lock object is executed. This thread will release the object lock and enter the waiting pool of the object. A deadlock occurs when a thread waits for the lock held by another thread while the latter is waiting for the lock held by the first thread. JVM does not monitor or try to avoid this situation, so it is the responsibility of programmers to ensure that no deadlock occurs. How to avoid deadlock A general rule of thumb is: when several threads want to access Shared resources A, B, and C, ensure that each thread accesses them in the same order. Thread communication Java. lang. two Methods for thread communication are provided in the Object class. 1. wait (): the thread that executes the method releases the lock of the Object, and the JVM places the thread in the waiting pool of the Object. This thread waits for other threads to wake up. 2. Wait y (): the thread that executes this method wakes up a thread waiting in the waiting pool of the object. The JVM selects a thread randomly from the waiting pool of the object, convert it to the lock pool of the object.

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.