简体   繁体   中英

Access string from outside a thread

I am new to java world and and I've been trying to find answer to this question and couldn't. So can someone explain how can I use already initialized String from outside a thread. Here is the code the string I want to use is "name" but if I make "name" final I can't set value to it.

public class Users {

    public static void GenerateNames() {

        String name = "";
        String str;
        for (int i = 0; i <= 2; i++)

            name = name + RandNames.GenerateRandomChar();

        str = name;

        Hashtable ht = new Hashtable();

        if (ht.get(str) == null)
        {
            ht.put(str, name);
        }
        else {

        }

        Runnable r = new Runnable() {
            public void run() {

                int Anketa = (int) (1 + Math.random() * 6);

                Hashtable voting = new Hashtable();

                if (voting.get(name) == null)
                {

                }
            }
        };
        new Thread(r).start();
    }
}

Also is there a problem that I left "else" empty. I just need it to do nothing.

Just move the code that generates name into a separate method:

public static String GenerateRandomName() {
    StringBuilder name = new StringBuilder();
    for (int i = 0; i <= 2; i++) {
        name.append(RandNames.GenerateRandomChar());
    }
    return name.toString();
}

The you'll be able to make name final:

public static void GenerateNames() {
    final String name = GenerateRandomName();
    ...
}

Also is there a problem that I left "else" empty. I just need it to do nothing.

Just omit it altogether:

if (ht.get(str) == null)
{
    ht.put(str, name);
}

In order to use name variable inside the run method you can declare this variable as a member of the Users class and mark it as static because it is used in static scope.

public class Users {

private static String name = "";

public static void GenerateNames() {

    // your code

    Runnable r = new Runnable() {
        public void run() {
            int Anketa = (int) (1 + Math.random() * 6);
            Hashtable voting = new Hashtable();
            if (voting.get(name) == null) {

            }
        }
    };
    new Thread(r).start();
}

}

One way to solve this type of problem is to use a second local variable:

public static void GenerateNames() {

    String workName = "";  // you can probably think of a better variable name
    for (int i = 0; i <= 2; i++)
        workName = workName + RandNames.GenerateRandomChar();

    final String name = workName;

and now you can use name in your anonymous inner class. (This is a pattern I use fairly often.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM