简体   繁体   中英

How can I make this method return an array?

How can I make the following method return a character array ?

public char[] startThread() {
    // arr declaration
    Runnable r = new Runnable() {
        @Override
        public void run() {
            arr = getArray(); // arr assignment
        }
    };
    new Thread(r).start();
    return arr;
}

char arrNew[] = startThread();

Note : The above snippet generates an error

Look for java.util.concurrent.Callable, its similar to runnable but returns a value.

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Callable.html

or

If in 1.6 JDK, you can look for Future objects.

You cannot do that.

When you return from your method, you don't have your char array. It is not created yet. So, assigning as a reference will not work. Neither Callable will help on this.

What you can do is that you create a holder object, and return that (this is very similar to Future objects):

public static class ArrayHolder {
    public char[] arr;
}

public ArrayHolder startThread() {

    final ArrayHolder holder = new ArrayHolder();

    Runnable r = new Runnable() {
        @Override
        public void run() {
            holder.arr = getArray(); // arr assignment
        }
    };
    new Thread(r).start();
    return holder;
}

ArrayHolder h = startThread();
char arrNew[] = h.arr;

Notice, that h.arr will change in time, so the first time you call it it will most likely return null

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