0

I am pretty new to Java and the project I have requires a new thread to be created every time the user presses a button. I've worked with the MVC and Swing but I am trying to find a way to create however many threads the user needs. I reviewed some information and was trying to use an arrayList to just collect all the threads. However I am having some problems with this:

private ThreadLibrary thread_lib = new ThreadLibrary(); 

    public TestArray(int val) {
        for (int i=0; i < val; i++) {           
            thread_lib.addThread(    new Thread(new runThread()).start()   );       
        }
    }

Since the new operator doesn't return anything it won't add anything to the arrayList. Any ideas or a better data structure to use? Thanks

3 Answers 3

1

new definitely returns whatever you're constructing. It's the start method which returns void. Try storing the thread object in a variable and kicking it off separately.

public TestArray(int val) {
    for (int i = 0; i < val; i++) {       
        Thread thread = new Thread(new runThread());
        thread.start();
        thread_lib.addThread(thread);       
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help and the clarification on what is returning void.
1

This,

thread_lib.addThread(    new Thread(new runThread()).start()   )

should be,

Thread t =  new Thread(new runThread());
thread_lib.addThread(t);
t.start();

Instead of doing this, look at the ThreadPoolExecutor class

2 Comments

one more question. Is there an easy way to pass any paramters to the runThread class? If I put it in new runthread() it shouldn't really be usable since t.start will kick off the run() method.
Ok - it seems to work but I guess don't really understand why. I assume it runs the constructor before it becomes a thread and goes to run(). Not sure if that will work for me in the long run.
0

new does indeed return the Thread; it's the call to start() that returns void. You can simply do this in two steps:

Thread t = new Thread(new runThread());
t.start();
thread_lib.addThread(t);

Now, whether you actually need to put these in an array or not is open to question; there isn't too much you can do to a Thread after it's running.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.