Use and learning of synchronize locks in java multithreading, Thread multithreading Learning (2), synchronizethread

Source: Internet
Author: User

Use and learning of synchronize locks in java multithreading, Thread multithreading Learning (2), synchronizethread

Synchronize I understand is to ensure atomicity and consistency in the program, that is, when you have two threads to operate a piece of code at the same time, make sure that the execution of this Code is correct in any State. First, make sure that synchronize is used for the same object and the same lock.

 

[Java]View plain copy print?
  1. <Span style = "font-size: 14px;"> public class TraditionalThreadSynchronized {
  2. Public static void main (String [] args ){
  3. TraditionalThreadSynchronized test = new TraditionalThreadSynchronized ();
  4. Test. init (); // create the same object
  5. }
  6. Private void init (){
  7. OutPuter outPuter = new OutPuter ();
  8. New Thread (new Runnable (){
  9. @ Override
  10. Public void run (){
  11. Try {
  12. While (true ){
  13. Thread. sleep (10 );
  14. OutPuter. outer ("abcdefg ");
  15. }
  16. } Catch (InterruptedException e ){
  17. E. printStackTrace ();
  18. }
  19. }
  20. }). Start (); // thread 1
  21. New Thread (new Runnable (){
  22. @ Override
  23. Public void run (){
  24. Try {
  25. While (true ){
  26. Thread. sleep (10 );
  27. OutPuter. outer ("123456789 ");
  28. }
  29. } Catch (InterruptedException e ){
  30. E. printStackTrace ();
  31. }
  32. }
  33. }). Start (); // thread 2
  34. }
  35. Class OutPuter {
  36. Public synchronized void outer (String name ){
  37. For (int I = 0; I <name. length (); I ++ ){
  38. System. out. print (name. charAt (I ));
  39. }
  40. System. out. println ();
  41. }
  42. }
  43. } </Span>


The output result we want to print is abcdefg and 123456789, but the output result is

 

 

We found that the printed results are printed alternately by two strings, so this thread is not safe now, so we need to use synchronize to maintain the atomicity of the two threads, next, let's add the synchronize lock to the OutPut method in the above program.

 

[Java]View plain copy print?
  1. <Span style = "font-size: 14px;"> class OutPuter {
  2. Public void outer (String name ){
  3. Synchronized (name ){
  4. For (int I = 0; I <name. length (); I ++ ){
  5. System. out. print (name. charAt (I ));
  6. }
  7. System. out. println ();
  8. }
  9. }
  10. } </Span>



 

We found that this thread is not safe after the lock with the synchronize keyword is applied. Why? The reason lies in the lock name, because one of the two threads is abcdefg and the other is 123456789. The two locks are not a lock at all, so the thread is also insecure, then let's modify the above method.

 

[Java]View plain copy print?
  1. <Span style = "font-size: 14px;"> class OutPuter {
  2. Public void outer (String name ){
  3. Synchronized (this) {// or create a new lock. You can change this to a lock. Here this refers to the outer object.
  4. For (int I = 0; I <name. length (); I ++ ){
  5. System. out. print (name. charAt (I ));
  6. }
  7. System. out. println ();
  8. }
  9. }
  10. } </Span>


At this time, we found that the program running above will not have thread security issues.

 

We can add the above syn to the outer at this time.

 

[Java]View plain copy print?
  1. Class OutPuter {
  2. Public synchronized void outer (String name ){
  3. For (int I = 0; I <name. length (); I ++ ){
  4. System. out. print (name. charAt (I ));
  5. }
  6. System. out. println ();
  7. }
  8. }

This can also achieve thread security, but under normal circumstances, synchronize only needs to be used once in a piece of code, because multiple synchronize may have a deadlock problem!

 

Now let's modify the OutPuter class above.

 

[Java]View plain copy print?
  1. Class OutPuter {
  2. Public void outer (String name ){
  3. Synchronized (this ){
  4. For (int I = 0; I <name. length (); I ++ ){
  5. System. out. print (name. charAt (I ));
  6. }
  7. System. out. println ();
  8. }
  9. }
  10. Public synchronized void outer2 (String name ){
  11. For (int I = 0; I <name. length (); I ++ ){
  12. System. out. print (name. charAt (I ));
  13. }
  14. System. out. println ();
  15. }
  16. Span style = "font-size: 14px;" >}</span>

 

Then, change outPuter. outer ("123456789") to outPuter. outer2 ("123456789 ")

 

 

 

Can thread security be ensured at this time, that is, will output and output2 be mutually exclusive? Of course, it is also possible, because the two locks at this time also represent the same lock, both represent the current object, and the current object is an object at this time, so we can achieve the desired effect.

 

In this case

 

Change outPuter. outer ("123456789") to new outPuter (). outer ("123456789 ")

 

 

We will find that there will still be thread security issues. Why? That's because the new OutPuter () is not the same object each time. Therefore, synchronize must be the same object and the same lock.

Now let's add an output3 method.

 

 

[Java]View plain copy print?
  1. Public static synchronized void outer3 (String name ){
  2. For (int I = 0; I <name. length (); I ++ ){
  3. System. out. print (name. charAt (I ));
  4. }
  5. System. out. println ();
  6. Span style = "font-size: 14px;" >}</span>

 

Note that the output3 method is static, so we need to change the OutPuter class to a static class.

 

Then, change outPuter. outer ("123456789") to outPuter. outer3 ("123456789 ")

 

 

The answer is no, because the lock in output3 we use is a class lock, and the lock in output is the current object lock, which is not a lock at all, so what should we do if we want to synchronize output and output3? We can change this in output to OutPuter. class to implement synchronization. At this time, the locks of both methods are class locks, that is, the same lock.

The thread is still learning, and learning is painful, but I hope I can really stick to one thing!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.