In this chapter we will discuss the critical section.
In general, we use multithreading directly on the method to add synchronized, but in fact, some time for performance, there is a lack of, so today to discuss the critical area of the problem.
1. Examples of general practices
Class Threada implements Runnable {private synchronized void Test () throws Interruptedexception {System.out.println (" DoSomething "); Thread.Sleep (5000); System.out.println ("dosomething");} @Overridepublic void Run () {while (true) {try {test ()} catch (Interruptedexception e) {e.printstacktrace ();}}}}
The above code is our general practice, of course, I will extend the above time some, but have not thought, in fact, in the first dosomething place, we do not need to thread safety (for example, most of the time is the function of querying the database, does not involve modification), While the second dosomething requires thread safety, because the entire approach requires thread safety, other threads cannot execute other methods inside the method execution, if the method needs to be executed for a long time (for example, the above Thread.Sleep (5000);), There is a problem with performance at this point, so we introduce the concept of a critical section.
2. What is a critical section?
The code area that causes the race condition to occur is called the critical section.
Which is the second dosomething above, we just need to do thread safety here.
3. How to make critical section thread safe?
(1) Use synchronized, because synchronized can be used not only in the method, but also in the code block, class above
Class Threada implements Runnable {private void Test () throws Interruptedexception {System.out.println ("dosomething"); Thread.Sleep (synchronized) {(this) {//thread synchronized Place System.out.println ("dosomething");}} @Overridepublic void Run () {while (true) {try {test ()} catch (Interruptedexception e) {e.printstacktrace ();}}}}
(2) using Reentrantlock
Class Threada implements Runnable {private Reentrantlock Reentrantlock = new Reentrantlock ();p rivate void Test () throws in terruptedexception {System.out.println ("dosomething"); Thread.Sleep (Reentrantlock.lock); try {System.out.println ("dosomething");} finally {Reentrantlock.unlock ();}} @Overridepublic void Run () {while (true) {try {test ()} catch (Interruptedexception e) {e.printstacktrace ();}}}}
Summary: This chapter mainly describes the use of critical areas.
This chapter is here, thank you.
-----------------------------------
Directory
Understanding java-18.5 critical area from the beginning