简体   繁体   English

Java中实现多线程

[英]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.我对 Java 很陌生,我的项目需要在每次用户按下按钮时创建一个新线程。 I've worked with the MVC and Swing but I am trying to find a way to create however many threads the user needs.我使用过 MVC 和 Swing,但我正在尝试找到一种方法来创建用户需要的多个线程。 I reviewed some information and was trying to use an arrayList to just collect all the threads.我查看了一些信息并尝试使用 arrayList 来收集所有线程。 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.由于运算符不返回任何内容,因此不会向 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不要这样做,而是查看ThreadPoolExecutor class

new definitely returns whatever you're constructing. new肯定会返回您正在构建的任何内容。 It's the start method which returns void .它是返回voidstart方法。 Try storing the thread object in a variable and kicking it off separately.尝试将线程 object 存储在变量中并单独启动它。

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 ; new确实返回了Thread it's the call to start() that returns void.是对start()的调用返回 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.线程运行后,您无能为力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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