Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the knowledge points of java concurrency

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "what are the knowledge points of java concurrency". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the knowledge points of java concurrency".

I. basic knowledge

1. The currenThread () method returns information about which thread the code snippet is being called.

2. Multithreading integrates Thread OR to realize Runable.

3. The function of isAlive () is to determine whether the current thread is active (that is, the thread starts and has not been terminated).

4. The function of sleep () is to hibernate the "executing thread" within a specified number of milliseconds (pause execution, release cpu without releasing the lock)

5. The function of getId () is to obtain the unique identity of the thread

6. Inerrupt () is used to stop the thread, but the interrupt () method does not work like for+break, which immediately stops the loop. Calling the interrupt () method tightly marks a stop in the current thread, not stopping the thread.

7. To determine whether the thread is stopped, Thread provides two methods, interrupted (): test whether the current thread has been interrupted (this method clears the interrupted state after execution). IsInterruopted (): test whether the thread has been interrupted (the status flag is not clear after execution).

8. You can interrupt the thread with an exception method (first judge isInterruopted () and then throw an exception)

9. If the thread is in the sleep () state and the thread is interrupted at this time, an exception will be thrown and the stop status value will be cleared.

10, violence to stop the thread method, stop () stop the thread is very violent, has been abandoned, because the forced stop of the thread may lead to some rational work can not be completed. In addition, the locked object is "unlocked", resulting in data can not be synchronized, resulting in the problem of data inconsistency.

11. You can use the suspend () method to pause the thread and the resume () method to resume thread execution. This method does not release the lock, only the cpu. If used improperly, it is easy to cause the monopoly of the common synchronization object and make it impossible for other threads to access the common synchronization object. It is also possible to cause data out of sync (not with locks).

12. The function of the yield () method is to discard the current CPU resource and let it be executed by another task. But the time to give up is uncertain, it is possible to just give up, and immediately get the CPU time slice.

13. You can set the priority of a thread through the setPriority () method, and the higher the priority, the earlier it will be executed. Priority can be inherited, and priority is random (there is no guarantee that a low priority will be executed after a high priority)

14. The daemon thread is a special thread, and its characteristics have the meaning of "companionship". If there is no non-daemon thread in the current thread, the daemon thread will be destroyed automatically. A typical daemon thread is a garbage collection thread.

Second, concurrent access to objects and variables

1. The "non-thread safety" problem exists in the instance variables. If it is a private variable within the method, there is no non-thread safety problem.

2. What synchronized adds to the method is a class lock, and different objects have different activities. But other threads in the same class can call non-synchronized methods asynchronously

3. Synchronized lock reentry, that is, when using synchronized, when a thread gets an object lock, it can get the object lock again when it requests the object lock again. This also proves that a lock can always be obtained when other synchronized methods / blocks of this class are called inside a synchronized method / block.

4. If reentrant can not be locked, it will cause deadlock, and reentrant lock also supports inheritance in parent and child classes.

5. When an exception occurs in the code executed by a thread, the lock it holds is automatically released.

6. When using the synchronized keyword to declare method synchronization, the disadvantage is obvious from the point of view of time. To solve this problem, you can use synchronized synchronization block.

7. When using synchronous synchronized (this) code blocks, it should be noted that when one thread accesses a synchronized (this) synchronization block of Object, other threads' access to all other synchronized (this) code blocks in the same Object will be blocked, indicating that synchronized uses an object monitor.

8. Like the synchronized method, the synchronized (this) code block locks the current object.

9. When multithreading calls the same object's synchronized synchronization method with different names or synchronized (this) synchronization code block, the effect of the call is executed sequentially, that is, synchronization blocking.

10. Java also supports synchronized (non-this objects). The advantage is that it does not compete with other synchronized (non-this objects) for this locks. The main function of the volatile keyword is to make variables visible across multiple threads

11. Under the premise of synchronized (x), there is a synchronization effect when multiple threads execute synchronized (x) {} synchronous code blocks at the same time. The synchronization effect occurs when other threads execute the synchronized synchronization method in the x object. Synchronization also occurs when other threads execute the synchronized (this) code block in the x object method

12. The keyword synchronized can also be applied to the static static method. If written in this way, it locks the Class class corresponding to the current * .java file, that is, all the resulting object instances are synchronized.

13. If synchronized public static and synchronized public hold different locks, one is class lock and the other is object lock

14. The function of synchronizing synchronized (class) code blocks is actually the same as that of the synchronized static method, which is to acquire class locks.

15. When using the synchronized (String) synchronization block with string, you should pay attention to some exceptions brought by the constant pool. The acquisition of the lock for the same character may be the same

Deadlock is the program bug, which should be designed to avoid the situation that both parties hold each other's locks. You can use JDK's native tools to detect deadlocks. Use the JPS command to find the thread ID,jstack-l id to view the results

The main function of the volatile keyword is to make variables visible across multiple threads. The thread stack is private to each thread, and using volatile will force you to get values from the public stack.

18. Using the volatile keyword increases the visibility of instance variables across multiple threads. But the deadliest drawback of the volatile keyword is that it does not support atomicity. Similar operations such as iTunes + are not supported.

The keyword volatile is a lightweight implementation of thread synchronization, so its performance is definitely better than synchronized, and volatile can only be modified on variables, while synchronized can decorate methods and code blocks. With the release of the new version of JDK, synchronized has greatly improved its execution efficiency.

20. Multithreaded access to volatile will not block, but synchronized will block.

Volatile can guarantee the visibility of data, but not atomicity, while synchronized can guarantee atomicity or indirectly, because it synchronizes the data in private memory and public memory.

22. The volatile keyword addresses the visibility of variables among multiple threads, while the synchronized keyword addresses the synchronization of access to resources between multiple threads.

23. Atomic operations can use AtomicInteger.incrementAndGet (), etc.

III. Inter-thread communication

1. The function of the wait () method is to make the currently executing thread wait. The wait () method is the method of the Object class, which is used to place the current thread in the "pre-execution queue" and stop execution at the code where wait () is located, until it is notified or interrupted. Before calling wait () again, the thread must acquire an object-level lock on the object, that is, the wait () method can only be called in a synchronization method or synchronization block. After executing the wait () method, the current thread releases the lock. Before returning from wait (), the thread competes with other threads to regain the lock. If the call to wait () does not hold the appropriate lock, IllegalMonitorStateException is thrown, which is a word class of runtimeException, so try-catch is not required

2. The notify () method is also called in a synchronous method or block, that is, the thread must also acquire an object-level lock on the object before it is called. If the call to notify () does not get the appropriate lock, an IllegalMonitorStateException exception is also thrown. This method is used to notify other threads that are likely to wait for the object lock of the object, and if there are multiple threads waiting, the thread planner randomly selects one of the objects in wait state (the higher the thread level, the greater the probability of acquisition), nontify () notification to it, and causes it to acquire the object lock.

3, after the execution of notify (), the current thread will not release the object lock immediately, and the thread in the wait state can not acquire the object lock immediately. It needs to wait for the thread of the notify () method to finish the execution of the program, that is, after exiting the synchronized code block, the current thread will release the lock, and the thread in the wait state can acquire the object lock. When the first wait thread that acquires the object lock finishes running, it releases the object lock. If the object does not use the notify () statement again, even if the object is idle, other wait state threads will continue to block in the wait state until the object issues a notify or notifyAll.

4. The wait () method enables the thread calling the method to release the lock on the shared resource, then exit from the running state and enter the waiting queue until it is awakened again.

5. The notify () method can randomly wake up a thread waiting for the same shared resource in the waiting queue and make the thread exit the waiting queue and enter the runnable state.

6. The notifyAll () method can make all threads waiting in the waiting queue waiting for the same shared resource exit from the waiting state and enter the runnable state. At this point, the thread with the highest priority executes first, but it may also be random, depending on the JVM implementation.

Illustration:

1) after creating a new thread object, call its start () method, and the system allocates CPU resources to the thread so that it is in a Runnable (runnable) state, which is a stage ready to run. If the thread grabs the CPU resource, the thread is in the Running state.

2) Runnable state and Running state can be switched between each other, because it is possible that after a thread has been running for a period of time, other high-priority threads preempt CPU resources, and the thread changes from Running state to Runable state. The thread entering the Runnable state is generally divided into the following five situations: (in fact, it is ready to preempt the state of CPU) the time elapsed after calling the sleep () method exceeds the specified sleep time. The blocking IO called by the thread has returned, and the blocking method has been successfully executed. The thread successfully obtains that the monitor thread trying to synchronize is waiting for a notification. The other thread issued a notification that the thread in the suspended state called the resume recovery method

3) Blocked means blocking, for example, when an IO operation is encountered, when the CPU is idle, the CPU time slice may be allocated to other threads, which can also be called a "paused" state. After the end of the Blocked state, enter the Runable state and wait for the system to reassign resources. There are five kinds of blocking situations: the thread calls the sleep () method, and the thread that actively abandons the occupied processor resources calls the blocking IO method. Before the method returns, the blocked thread tries to obtain a synchronization monitor, but the synchronization monitor is being held by another thread while waiting for a notification thread to call the suspend () method to suspend the thread. This method can easily lead to deadlock and try to avoid using it.

4) after the run () method finishes running, it enters the destroy phase, and the entire thread finishes execution.

Each lock object has two queues, one is the ready queue and the other is the blocking queue. The ready queue stores the thread that is about to acquire the lock, and the blocking queue stores the blocked thread. After a thread is awakened, it enters the ready queue (Runable state) and waits for CPU scheduling; conversely, after a thread is wait (), it enters the blocking queue and waits for the next wake up.

8. When a thread is in a wait state, an InterruptedException exception occurs when calling the thread object's interrupt () method.

9. The function of the wait (long) method with one parameter is to wait for a thread to wake it up at a certain time, and automatically wake it up if it exceeds this time.

10. PipeStream is a special stream that is used to transfer data directly between different threads. One thread sends data to the output pipe, and the other thread reads data from the input pipe. Through the use of pipes, communication between different threads is achieved without the need for temporary files and the like.

11. JDK provides four classes to enable communication between threads 1) PipedInputStream and PipedOutputStream 2) PipeReader and PipedWriter

12. Use the code inputStream.connect (outputStream) or outputStream.connect (inputStream) to create a communication link between the two Stream, so that the data can be transferred.

The main function of the method join () is to wait for the thread object to be destroyed.

14. The function of the method join () is to make the thread object X execute the task in the run () method normally, and make its current thread Z block indefinitely, waiting for thread X to be destroyed before continuing to execute the code behind thread Z.

15. The method join () has the function of queuing threads to run, which is similar to the effect of synchronization. The difference between join and synchronized is that join internally uses the wait () method to wait, while the synchronized keyword uses object monitor principles for synchronization.

16. An exception occurs when join () and interrupt () encounter.

17. The main problem of class ThreadLocal is that each thread binds its own value. ThreadLocal class can be compared to a global data storage box, in which private data of each thread can be stored.

18. The first call to the get () method of ThreadLocal returns a value of null. If you don't want the default value to return to null, you can integrate ThreadLocal to override the initialValue () method.

19. InheritableThreadLocal can get the value inherited by the parent thread in the child thread. If the main thread changes the value while the child thread gets the value, the child thread gets the old value.

Thank you for your reading, the above is the content of "what are the knowledge points of java concurrency". After the study of this article, I believe you have a deeper understanding of what the knowledge points of java concurrency have, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report