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 is synchronized?

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

Share

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

This article mainly explains "what is synchronized". 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 is synchronized".

Synchronized usage

As mentioned above, synchronized can be written on a method or a code block, but the type of lock may be different. if written on a method, the lock is the object of the current class, and you can specify the object of the lock when used on the code block. If acting on a static code block, the class object of the specified class is locked.

The synchronized lock is fully automatic, which is automatically locked and unlocked, and if an exception is thrown during the execution of the code, synchronized will automatically release the lock

The synchronized lock is a reentrant lock, that is, the current thread calls method A, and method B is called in method A, which can be called directly without competing locks. Jvm is also designed to prevent deadlocks, so here you can also understand why when the current thread accesses method A, other threads cannot access other methods. In other words, when the T1 thread accesses method A, the T2 thread also accesses method A, which is definitely not allowed, needless to say, because the object locked is an object locked by the T1 thread, and the T2 thread certainly cannot acquire the lock. Similarly, when the T2 thread accesses the B method, isn't the same object locked in the B method, that is, the T2 thread also has to acquire the lock of the object locked by the T1 thread in the A method.

Threadlocal thread private variables, for example, you know:

Public class ThreadLocalTest {class Person {String name = "zhangsan";} @ Test public void threadLocal1 () {ThreadLocal tl = new ThreadLocal (); Person person = new Person (); tl.set (person) New Thread (new Runnable () {@ Override public void run () {System.out.println ("New Thread" + tl.get ();}}) .start () System.out.println (tl.get ()); try {TimeUnit.SECONDS.sleep (2);} catch (InterruptedException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}

The newly started thread prints person as null, that is, objects set through threadlocal can only be used in the current thread, and other threads get null.

Volatile keyword, please click Jump

Let's focus on notify and wait, because the hole in it fell into it a little inadvertently. I wrote an article before, and I'll give another example of producers and consumers: demand: there are 2 producer threads and 10 consumer threads. If the container is full, the producer pauses. If the container is empty, the consumer pauses.

Public class ProducerAndConsumer {/ / has 2 producer threads and 10 consumer threads. If the container is full, the producer pauses. If the container is empty, the consumer pauses final private LinkedList list = new LinkedList (); final private int maxValue = 10; / * producer, as required: stop when the container is full. * / public synchronized void producer (Object o) {/ * was originally implemented with if, but why change it to if and while: (this is a pit, it's easy to fall into it) * 1. You know, if at this point, the container is full, and then the first thread comes here, judge the if logic, then execute the wait method to wait, and [release the current object lock] * 2. Then which thread is called by cpu is randomly selected, and if another producer thread is called at this time, the wait method is also executed. * 3. At present, there are two threads in wait, and then the cpu execution consumer thread consumes one, and now there are still nine in the container. * then the consumer thread wakes up the thread through notifyall, waking up the two producer threads, so: * 3.1 first, the first producer thread starts execution, starts execution from wait, and adds elements. The container is full again, release the lock * 3.2 and then the second producer thread starts execution, which starts from wait, because the while loop is not used, so * it will execute directly, that is, add elements, so the container size is not 10. * 4. Therefore, 99% of the scenarios using wait are used in conjunction with the while loop * 5. If wait and notify are not written in the synchronized lock, the IllegalMonitorStateException exception will be thrown, but * why does it have to be in the synchronized lock? then it is certain that the wait call will occur after the call to notify. [reference blog] (https://www.cnblogs.com/set-cookie/p/8686218.html) * / / if (list.size ()) = = maxValue) {while (list.size () = = maxValue) {try {this.wait () } catch (InterruptedException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}} list.add (o) / / there is something in the container that wakes up the waiting thread to consume (the waking thread includes the producer thread and the consumer thread). The main purpose is the consumer thread this.notifyAll () } / * Consumer * / public synchronized Object consumer () {while (list.size () = = 0) {try {this.wait () } catch (InterruptedException e) {/ / TODO Auto-generated catch block e.printStackTrace () } / / I took something and woke up the waiting thread to produce (the waking thread includes the producer thread and the consumer thread). The main purpose is the producer thread Object o = list.removeFirst (); this.notifyAll (); return o } public static void main (String [] args) {ProducerAndConsumer pcTest = new ProducerAndConsumer (); / / start the consumer thread for (int iThread 0 I {for (int job0 j)

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