Why String designed to be immutable

I think that the main reason for a need to string pool

String pool area is a special storage area method (Method Area) in. When a string and the string has been created in the pool, the reference to the string is returned immediately to the variable, instead of re-creating a string and then returns a reference to the variable. If the string is not immutable, then changing a reference (eg: string2) will result in a string of a reference to another (eg: string1) have stale data.

Many people say the Internet is because when the thread-safe multi-threaded, I think this is inexplicable

public class Test {
    private final String TAG = "Test";
    private String value = "hello";

    public void test1() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                value = "test1";
                Log.e(TAG," value=" + value);
            }
        });
    }

    public void test2() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                value = "test2";
                Log.e(TAG," value=" + value);
            }
        });
    }
}

In the above code, test1, test2 are running two threads, this value is the time value of uncertainty, whether string is not immutable

 

 

 

Guess you like

Origin blog.csdn.net/dxh040431104/article/details/92838962