开发者

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 a开发者_运维技巧nd 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


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


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 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜