Java Multithreading Summary Four: volatile, synchronized example

Source: Internet
Author: User

1, Synchronized guarantee synchronization

Let's look at a class that generates even numbers.

[Java]View Plaincopy
  1. <span style="FONT-SIZE:16PX;"  > Packagedemo.thread;
  2. /**
  3. * This is an abstract class for an int generator
  4. *
  5. */
  6. Public Abstract class Intgenerator {
  7. Private volatile Boolean canceled = false;
  8. public Abstract int next ();
  9. public void Cancel () {
  10. Canceled = true;
  11. }
  12. Public Boolean isCanceled () {
  13. return canceled;
  14. }
  15. }
  16. </span>


[Java]View Plaincopy
  1. <span style="FONT-SIZE:16PX;" >/*
  2. * Generate even numbers
  3. */
  4. Class Evengenerator extends Intgenerator {
  5. private int currentevenvalue = 0;
  6. String s = "";
  7. @Override
  8. public int Next () {
  9. <span style="color: #ff0000;" >synchronized </span> (s) {
  10. ++currentevenvalue;
  11. ++currentevenvalue;
  12. return currentevenvalue;
  13. }
  14. }
  15. This can also
  16. Public <span style= "color: #ff0000;" >synchronized </span>int Next () {
  17. ++currentevenvalue;
  18. ++currentevenvalue;
  19. return currentevenvalue;
  20. //  }
  21. }</span>


Note that in the generation of even is to add a synchronous lock, or maybe thread 1 just executed a sentence of ++currentevenvalue, the operation, the thread 2 was robbed of the CPU, the thread 2 executes return currentevenvalue, then returned is an odd number. Plus synchronized is the code of two threads that can execute synchronized blocks at the same time only one thread .

Test code:

[Java]View Plaincopy
  1. <span style="FONT-SIZE:16PX;"  > Packagedemo.thread;
  2. Import Java.util.concurrent.ExecutorService;
  3. Import java.util.concurrent.Executors;
  4. /*
  5. * Consumption figures
  6. */
  7. Public class Evenchecker implements Runnable {
  8. private Intgenerator Generator;
  9. private final int id;
  10. Public Evenchecker (intgenerator g, int ident) {
  11. Generator = g;
  12. id = ident;
  13. }
  14. public Void Run () {
  15. While (!generator.iscanceled ()) {
  16. int val = Generator.next ();
  17. if (val% 2 = 0) {//If not even
  18. System.out.println (val + "not enen!");
  19. Generator.cancel ();
  20. }
  21. }
  22. }
  23. public static void Test (Intgenerator GP, int count) {
  24. Executorservice exec = Executors.newcachedthreadpool ();
  25. For (int i = 0; i < count; i++)
  26. Exec.execute (New Evenchecker (GP, i));
  27. Exec.shutdown ();
  28. }
  29. public static void Test (Intgenerator gp) {
  30. Test (GP, 10);
  31. }
  32. public static void Main (string[] args) {
  33. Test (New Evengenerator ());
  34. }
  35. }</span>


Analysis: If the class that produces even numbers is not synchronized, then the test program will appear odd to cause the program to exit.

2, volatile indicates atomicity, visibility.

For variables shared between multiple threads, each thread has its own copy, and when thread 1 changes the value of the variable, other threads do not immediately know that the variable value has changed, and volatile guarantees that the value of the variable is visible to each thread, and that the value is changed by a thread in the other thread immediately. Atomicity indicates that the operation is not interruptible, such as the basic variable assignment.

code example:

[Java]View Plaincopy
  1. <span style="FONT-SIZE:16PX;"  > Packagedemo.thread;
  2. Public class Volatiledemo implements Runnable {
  3. Private volatile int i = 0; Volatile setting visibility
  4. public synchronized int GetValue () {
  5. return i;
  6. }
  7. private synchronized void Enenincrement () {
  8. i++;
  9. i++;
  10. }
  11. @Override
  12. public Void Run () {
  13. While (true)
  14. Enenincrement ();
  15. }
  16. public static void Main (string[] args) {
  17. Volatiledemo at = new Volatiledemo ();
  18. new Thread (at). Start ();
  19. While (true) {
  20. int val = At.getvalue ();
  21. if (val% 2 = 0) {//appears odd, exits the program
  22. System.out.println (val+"is not enen!");
  23. System.exit (0);
  24. }
  25. }
  26. }
  27. }
  28. </span>


Note that the i++ operation is not an atomic line operation, and the GetValue () method should also be added synchronized.

Java Multithreading Summary Four: volatile, synchronized example

Related Article

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.