Thread knowledge point summary

Source: Internet
Author: User

Java threads have two features:
Visibility and orderliness
Data Interaction cannot be transmitted between multiple threads. Interaction between threads can only be achieved through shared variables. An object of the Count class is shared among multiple threads. This object is created in the main memory (heap memory) and each thread has its own working memory (thread stack) the working memory stores a copy of the master memory count object. When the thread operates the Count object, it first copies the Count object from the master memory to the work memory, and then executes the code count. count () should change the num value, and then use the working memory count to refresh the master memory count. When an object has copies in multiple memories, if one memory modifies the shared variable, other threads should be able to see the modified value, which is visibility.
As we can see from the above, a value assignment operation is not an atomic operation. When multiple threads are executed, the CPU schedules threads randomly, we do not know where the current program is executed and switch to the next thread. The most typical example is the bank remittance problem. A bank account has a deposit of 100, at this time, a person will get 10 yuan from the account, and another person will remit 10 yuan to the account, then the balance should be 100. This may happen at this time. Thread A is responsible for withdrawal, thread B is responsible for remittance, and thread a reads 100 from the outbound memory. Thread B reads 100 from the primary memory, and a performs 10 minus operations, and refresh the data to the main memory. In this case, the data in the main memory is 100-10 = 90, while in the B memory, the data is refreshed to the main memory, and the data in the main memory is 100 + 10 = 110, obviously, this is a serious problem. We need to ensure that thread a and thread B are executed in an orderly manner. This is an order to make money after withdrawal or after remittance.
Multithreading: A thread is 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 the threads in the same process work in the same address space, these threads can share the same memory and system resources.
A thread can only be started once. The second startup will throw a java. Lang. illegalthreadexcetpion exception.
Five States of a thread:
1. New: the thread created with the new statement is in the new State. At this time, like other Java objects, it only allocates memory in the heap.
2. ready state (runnable): When a thread is created, other threads call its start () method, and the thread enters the ready state. The thread in this status is located in the runningpool, waiting for the CPU to be used.
3. Running status (running): the threads in this status occupy the CPU and execute the program code.
4. Blocked: When a thread is in a blocking state, the Java Virtual Machine will not allocate CPU to the thread until the thread enters the ready state.
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 will put the thread in the waiting pool of the object.
2) It is located in the blocking state of the object lock. When the thread is in the running state and 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 lock pool of this object.
3) Other blocking states: When the thread executes the sleep () method, or calls the join () method of another thread, or sends an I/O request, it will enter this status.
5. Dead: When the thread exits the run () method, it enters the dead state, and the thread ends its lifecycle. Or exit normally or encounter exceptions.
The isalive () method of the thread Class determines whether a thread is still alive. When the thread is in the dead or new state, the method returns false, and in other States, the method returns true.
Thread Scheduling Model:
Time-based scheduling model and preemption 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 the operating system)
 
If you want to explicitly give another thread a chance to run, you can take one of the following methods:
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

Adjust the priority of each thread
The setpriority (INT) and getpriority () Methods of the thread class are 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 it throws any exception.
4. The sleep () method has better portability than the yield () method.
 
Wait for the end of other threads: Join ()
The currently running thread can call the join () method of another thread. the currently running thread will be switched to the blocking state until the execution of another thread ends.
 
Timer: a Timer class timer is provided in the Java. util package of JDK, which can regularly execute specific tasks.

Thread Synchronization
Atomic operation: According to Java specifications, an atomic operation is used to assign values or return values to basic types. 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.
(Usually, the synchronization lock is not released when the synchronization code block is executed, but the object lock is also released in some special cases.
For example, when a synchronization code block is executed, the thread is terminated due to an exception, and 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 will release the object lock and enter 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 security 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 object lock:
1. After the synchronization code block is executed, the object lock will be released.
2. When a synchronization code block is executed, the thread is terminated due to an exception, and the lock is released.
3. During the execution of the synchronization code block, 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.
 
Deadlock
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 deadlocks
A general rule of thumb is that when several threads want to access Shared resources A, B, and C, ensure that each thread accesses them in the same order.
 
Thread Communication
The Java. Lang. object class provides two methods for thread communication.
1. Wait (): When the thread that executes this method releases the lock of the object, JVM will put the thread in the waiting pool of the object. This thread waits for other threads to wake up
2. Y (): the thread that executes this method wakes up a thread waiting in the waiting pool of the object, and the JVM selects a thread randomly from the waiting pool of the object, convert it to the lock pool of the object.

Thread priority
Thread priority range: 1-10. The JVM thread scheduler is a priority-based preemptive scheduling mechanism. In most cases, the priority of the currently running thread is greater than or equal to the priority of any thread in the thread pool. However, in most cases, when the threads in the thread pool have the same priority, the JVM Implementation of the scheduler selects the thread it prefers. At this time, there are two possible operations for the Scheduler: one is to select a thread to run until it is blocked or the execution is complete. Second, time slice provides equal operation opportunities for each thread in the pool.
Note: When designing multi-threaded applications, do not rely on the thread priority. Because the thread scheduling priority operation is not guaranteed, the priority of the thread can only be used as a way to improve program efficiency, but ensure that the program does not rely on this operation.
Set the thread priority: the default priority of a thread is the priority of the execution thread that creates it. You can use setpriority (INT newpriority) to change the priority of a thread. For example:
Thread t = new mythread ();
T. setpriority (8 );
T. Start ();
The thread priority is a positive integer between 1 and 10. JVM never changes the priority of a thread. The JVM never changes the priority of a thread. However, the quality inspection ticket values from 1 to 10 are not guaranteed. Some JVMs may not be able to identify 10 different values, and these priorities are merged every two or more, if the priority is less than 10, two or more priorities may be mapped to one priority.

The default thread priority is 5, and there are three constants in the Thread class, defining the thread priority range: static int max_priority thread can have the highest priority
The static int min_priority thread can have the lowest priority
Static int norm_priority default priority

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.