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

How to use the traditional thread mutex technology of synchronized

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

In this article, the editor introduces in detail "how to use synchronized traditional thread mutex technology". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to use synchronized traditional thread mutex technology" can help you solve your doubts.

When multiple threads operate the same resource at the same time, they will encounter concurrency problems, such as bank transfer, ticketing system and so on. To avoid these problems, we can use the synchronized keyword to solve them. Here is a summary of the common uses of synchronized. First, write a program with concurrency problems, as follows:

Public class TraditionalThreadSynchronized {public static void main (String [] args) {/ / cannot new instance objects of inner classes in static methods / / private Outputer outputer = new Outputer (); new TraditionalThreadSynchronized (). Init ();} private void init () {final Outputer outputer = new Outputer () / / Thread 1 print: duoxiancheng new Thread (new Runnable () {@ Override public void run () {while (true) {try {Thread.sleep (5)) } catch (InterruptedException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} outputer.output1 ("duoxiancheng");}) .start () / / Thread 2 print: eson15 new Thread (new Runnable () {@ Override public void run () {while (true) {try {Thread.sleep (5)) } catch (InterruptedException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} outputer.output1 ("eson15");}) .start () } static class Outputer {/ / customize a string printing method: public void output1 (String name) {int len = name.length (); for (int I = 0; I < len; iTunes +) {System.out.print (name.charAt (I));} System.out.println ("") }}}

In the inner class Outputer, a method of printing strings is defined, printing one character at a time, so it is easy to see the concurrency problem intuitively, because the disorder of the character order means that there is a problem. Then start two threads in the init method, one to print "duoxiancheng" and the other to print "eson15". Take a look at the results of the run:

Eson15duoxianche

Ng

Eson15

Duoxiancheng

Duoxiancheng

Eson15

Esduoxiancheng

On15

Duoxiancheng

As you can see from the output, there is already a problem. To solve this problem, you can use the synchronized synchronization code block to synchronize the common part, but you need to give it a lock, which is an object, which can be any object, but only if both threads use the same object lock, which is easy to understand. So let's add the synchronized code block to the output1 () method:

Static class Outputer {private String token = "" / / define a lock public void output1 (String name) {synchronized (token) / / any object can be used as a parameter, but the object is the same for two threads / / not if name is used, because different threads enter name differently, not the same name {int len = name.length () For (int I = 0; I < len; iTunes +) {System.out.print (name.charAt (I));} System.out.println ("");}

After the above modification, the thread safety problem is basically solved, but you can go further. If you add the synchronized keyword to the method, what is the synchronization lock? Let's write another output2 () method in the Outputer class:

Static class Outputer {private String token = ""; / / define a lock public void output1 (String name) {synchronized (token) / / any object can be used as a parameter, but the object is the same for two threads {int len = name.length (); for (int I = 0; I < len) Int +) {System.out.print (name.charAt (I));} System.out.println (");}} public synchronized void output2 (String name) {int len = name.length (); for (int I = 0; I < len; iTunes +) {System.out.print (name.charAt (I)) } System.out.println (");}}

The internal implementation logic of the method is exactly the same, except that synchronized is added to the method, so we let one of the two threads in the init () method call the output1 (Stringname) method and the other call the output2 (Stringname) method. The cause of the problem is not difficult to find: now both methods have added synchronized, but the two threads are still having problems calling two different methods, that is to say, they are still playing with each other. Then the problem lies in this lock, which means that the two do not use the same lock!

If we change the token in the synchronized in the output1 () method to this, we can run it again, which means that when the synchronized keyword modifies the method, the synchronization lock is this, which is equivalent to the code block synchronized (this) {.}.

To go further, now write a static method output3 (Stringname) in the Outputer class, and let synchronized decorate the static method as well.

Static class Outputer {private String token = ""; / / define a lock public void output1 (String name) {synchronized (token) / / any object can be used as a parameter, but the object is the same for two threads {int len = name.length (); for (int I = 0; I < len) Int +) {System.out.print (name.charAt (I));} System.out.println (");}} public static synchronized void output3 (String name) {int len = name.length (); for (int I = 0; I < len; iTunes +) {System.out.print (name.charAt (I)) } System.out.println (");}

Then in the init () method, one thread calls the output1 () method, and the other thread calls the output3 () method. There is no doubt that there will be thread safety problems again. But how to solve it? Because the static method is loaded when the class is loaded, the lock should be the bytecode object of the class. Then changing token to Outputer.class solves the problem, which shows that when the synchronized keyword modifies the static method, the synchronization lock is the bytecode object of the class, that is, equivalent to the code block synchronized (classname.class) {.}.

Finally, let's sum up:

The lock of the synchronization code block is any object. This lock is set at will as long as different threads execute the same synchronous code block.

The lock of the synchronization function is fixed this. When you need to synchronize with the logic in the synchronization function, the lock in the code block must be this.

The lock of a static synchronization function is the bytecode file object of the class to which the function belongs. This object can be obtained using the this.getClass () method or represented by the current class name .class.

After reading this, the article "how to use synchronized traditional thread mutex technology" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, welcome to follow the industry information channel.

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

Development

Wechat

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

12
Report