简体   繁体   中英

Implementing multiple threads in Java

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

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

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);       
    }
}

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.

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