Java thread, what is its answer?

The problem is from http://www.javacertifications.net/javacert/scjp1.6Mock.jsp start

No problem - 20

What is the output of the following code?

public class Test extends Thread
{   
    static String sName = "good";
    public static void main(String argv[])
    {
        Test t = new test();
        t.nameTest(sName);
        System.out.println(sName);    
    }
    public void nameTest(String sName)
    {
        sName = sName + " idea ";
        start();
    }
    public void run()
    {
        for(int i=0;i  <  4; i++)
        {
            sName = sName + " " + i;

        }
    }
}

B) good idea C) good idea the correct answer is: a

Explanation: in the case of string, the changed value in the local method will not change globally (because the string object is immutable)

Solution

No answer is right, and no answer is right

The problem is very bad because it mixes two completely different problems:

>The sname parameter of the nametest() method hides static variables with the same name, and changes to local variables are invalid. > Nametest () starts a thread that changes static variables in its run () method, while the main () method prints variables without waiting for the thread to complete This is called a race condition: the state of the variable to be printed is almost coincidental – any of the following is possible:

>Good > good 0 > good 0 1 > good 0 1 2 > good 0 1 2 3

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>