Java Fundamentals (ii) Self-increment self-reduction and greedy rules

Source: Internet
Author: User
Tags parse string


Introduction

?? The self-increment operator + + is available in the JDK, and the decrement operator--。 Each of these two operators is used in two ways: prefix (+ a,--a), suffix (a++,a--). May say here, said not to have the reader will Spit Groove said, the prefix is quite simple, the prefixes are not first +1 (or-1), and then use this value to participate in the operation, the suffix is the opposite. Is it necessary to be lengthy?
?? The difference between the front and back is true, at least on the surface, but a deeper understanding is not so simple, and even seriously affects the correctness of your program. Do not believe, go down to see it!


1. The true difference between prefix and suffix in Java

?? In Java, the operation is calculated from left to right, and according to the operator's priority, one by one to calculate the value of the expression, and use this value to participate in the next expression of the operation, such as:, in fact, the 1+2+3 first calculation 1+2 of the expression value of 3, and then participate in the next expression of the operation (1+2)+3 , namely 3+3 . Again as judged if(a+2==3) . So the analogy.
??a++ is an expression, then a++ there is an expression that evaluates to the old value of a (the value before 1 plus). In contrast, the ++a expression evaluates to a plus 1 value. Therefore, the intrinsic difference between the self-increment prefix form and the suffix form is that the value of the expression (the result of the operation) is the value of the variable that was added before 1 or the value of the variable after the addition of 1 (this is also the case with self-subtraction). Not first add 1 and then add 1 difference , or, the prefix form is added 1 (minus 1), only to get the value of the expression, and then participate in the next operation. Because this is an expression, the expression must be evaluated before the value of the expression is given .

Let's look at a frequently encountered interview question:

int a = 5;a = a++;//What is the value of a at this time?

?? Have you guessed the value of a? We have learned from the above analysis: a=a++ can be understood as follows several steps:

1. Calculate a from plus 1, i.e.a=a+1

2, calculate the value of the expression, because this is the suffix form, so a++ the value of the expression is added 1 before the value of a (the value is 5);

3. Assign the value of the expression to a, that is a=5 .

So the last value of a is 5.

Similarly, if you change a = ++a to a, then the value of a is 6. This is because ++a the value of the expression is a after 1 plus, that is, 6.


2. Self-increment and decrement are two operations, not thread-safe

?? The self-increment, decrement operator is essentially not a computation operation, but a two calculation operation. a++For example, this operation will parse the compiler into: a=a+1 two single-mesh operators (+, =), and a single-mesh operator can be considered an atomic operation. a++the steps can be described as:
?? 1, first take a plus 1, the results are stored in the temporary space;
?? 2. Assign the result to a. Therefore, the self-increment decrement operator contains two operations: an operation that adds 1 (minus 1) and an assignment operation

?? Does this principle seem to be useless for my programming? No, in a single-threaded environment, you can ignore the details. But in the case of multithreading, you have to keep this detail in mind all the time. You know, self-increment is not an atomic operation, that is, it is not a thread-safe operation. therefore, in multi-threading, if you want to implement self-decrement for shared variables, you need to lock it, or use the atomicity provided by the JDK-provided atomic operations class (such as AtomincInteger , AtomicLong etc.) to increase the self-decrement.

Let's take a look at the example and verify. The following example provides three static variables (an atomic operation Class), creates 10 threads, and each thread adds 1 operations to the three variables in different ways and loops 1000 times.

public class mytest {    static int a = 0;     static int b = 0;    //Atomic Operation class      Static atomicinteger atomicint = new atomicinteger (0);     public  static void main (String[] args)  throws InterruptedException {         for  (int i = 0; i < 10; i++)  {//Create a 10 thread             thread t =  new thread ()  {                  @Override                  public void run ()  {                     for  (int j = 0; j < 1000; j++)  {//Calculation 1000 times                          a = a + 1;                          b++;                         atomicint.incrementandget ();//self-increasing atomic method                      }                 }             };             t.start ();nbsp;       }        //  Determines whether the current active thread is not the only main thread, to ensure that 10 compute threads are executed.         while  (Thread.activecount ()  > 1)  {             thread.sleep (;   )      }        system.out.println ("a=a+ 1 The result under multithreading is: " + a";         system.out.println ("b++ in multi-threaded result is:" &NBSP;+&NBSP;B);         system.out.println (" The result of the atomic Operation class Atomicinteger under Multithreading is: " + atomicint.get ());     }}

Operation Result:

The results of a=a+1 under multithreading are: 8883
The results of b++ under multithreading are: 8974
The result of the atomic Operation class Atomicinteger under multithreading is: 10000

?? From the running results can be seen, a=a+1、b++ not thread-safe, did not calculate the correct result 10000. In other words, neither of these expressions is an atomic operation. As a matter of fact, they all contain two calculation operations.


3. Reflections on the expression of a+++b

?? Seeing this expression is really confusing: how does the compiler parse it and parse it into

a++ + b

Still is

A + ++b

Really tangled, simply run a trip directly to the compiler to see the results!

int a = 5;    int b = 5;    int c=a+++b;    System.out.println (the value of "a" is: "+a); System.out.println (the value of "B" is: "+b);

Operation Result:

The value of a is: 6
The value of B is: 5

?? From the results can be confirmed, in a+++b fact, is resolved into a++ +b , why should such a combination? There are actually two reasons:

    • The operations in Java are performed from left to right;

    • The Java compiler has a rule-greedy rule. In other words, the compiler will combine as many valid symbols as possible.

So, a+++b the way that this combination can explain

But this combination is: as many combinations as possible, regardless of whether such a combination is legal . Such as:

A--b

will be parsed by the compiler into

a--b

Although this is illegal, the compiler still handles this, which causes the compilation to pass, resulting in a compilation error.

Why should the compiler use greedy rules?

?? From the above analysis, greedy rules in programming is also not good use. So, what is the main purpose of the greedy rule?
?? The main purpose of the greedy rule is to parse string strings and see the following example to understand:

String s = "\17";    System.out.println (the value of the \\17 escape character is: "+s+" length is: "+s.length ()");    s = "\171";    System.out.println (the value of the \\171 escape character is: "+s+" length is: "+s.length ()");    s = "\1717";    System.out.println (the value of the \\1717 escape character is: "+s+" length is: "+s.length ()");    s = "\17178"; System.out.println (the value of the \\17178 escape character is: "+s+" length is: "+s.length ()");

Operation Result:

The value of the \17 escape character is:?? Length is: 1
The value of the \171 escape character is: Y?? Length is: 1
The value of the \1717 escape character is: Y7?? Length is: 2
The value of the \17178 escape character is: Y78?? Length is: 3

??“ \17 "escaped by a special character" ". A character "Y" is also obtained after "\171" is escaped. However, "\1717", "\17178" get the string greater than 1, is no longer a character, respectively, is "Y7", "y78".

?? That is, the "\1717" string only escapes the "\171" section and then links the "7" section. The "\17178" string only escapes the "\171" section and then connects "78".

?? So why does "\171" not escape the "\17" part, and then link "1", instead of escaping the string as a whole?

?? This is what the " greedy rules " determine. The value range of the octal escape character is \0~\377. So when parsing the "\171" string, the compiler combines as many characters as a transfer character, and "\171" is still within the range, so it's a character. However, the "\1718" string, which combines the first 4 characters into a valid escape character "\171", and "\1717" has exceeded the range of values, is not a valid character, so it is finally parsed as the result of "\171" + "7". The same is true of "17178".

4. Summary
    • When parsing characters, the compiler will combine as many valid characters as possible, but syntax errors may occur.

    • Greedy rules are useful, and the special compiler is the handling of escaped characters.

Source: http://www.cnblogs.com/jinggod/p/8424808.html

The article is inappropriate, please correct me, you can also pay attention to my public number: ' Learn Java ', access to high-quality learning resources.




Java Basics (ii) Self-increment and greedy rules

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.