Java's synchronization mechanism, presumably by:
1.synchronized;
Wait,notify in the 2.Object method;
3.ThreadLocal mechanism
, where synchronized is used in two ways:
1. Modifying the method of a class
2.synchronized (object) method for retouching
in the synchronization mechanism, the lock mechanism of the object guarantees that only one thread accesses the variable at the same time. At this time the variable is shared by multiple threads, using the synchronization mechanism requires the program to carefully analyze when to read and write variables, when to lock an object, when to release object locks and other complex problems, programming and writing is relatively difficult. threadlocal, however, solves multiple threads of concurrent access from another angle. Threadlocal provides a separate copy of the variable for each thread, isolating the access violation of multiple threads to the data. Because each thread has its own copy of the variable, there is no need to synchronize the variable. Threadlocal provides thread-safe shared objects that can encapsulate unsafe variables into threadlocal when writing multithreaded code.
of course, threadlocal can not replace the synchronization mechanism, the problem areas are different. The synchronization mechanism is to synchronize multiple threads for concurrent access to the same resource, which is an efficient way to communicate between multiple threads, while threadlocal is a data share that isolates multiple threads, and essentially does not share resources (variables) across multiple threads, which of course does not require synchronization of multiple threads. So, if you need to communicate between multiple threads, use the synchronization mechanism, and if you need to isolate sharing conflicts between multiple threads, you can use threadlocal, which greatly simplifies your program, making the program more readable and concise.
What are the ways to implement Java multithreading? How does a class in Java guarantee thread safety? Please describe the usage and application of threadlocal