简体   繁体   English

根据输入的数量在while循环中创建多个java线程

[英]create multiple java threads in a while loop depending on the number of inputs

i am trying to write a java programm that is reading informations out of a database and creates for every row of the table a new thread. 我正在尝试编写一个java程序,它从数据库中读取信息,并为表的每一行创建一个新线程。 So i dont know how much threads i will need. 所以我不知道我需要多少线程。 so far i have this: 到目前为止我有这个:

        con = DriverManager.getConnection(url, user, passwd);
        pst = con.prepareStatement("select hostname, ipadress, vncpassword from infoscreens");
        rs = pst.executeQuery();
        int i=0;
        while (rs.next()) {
            i++;
            Thread tread[i]  = new Savescreenshots(rs.getString(1),rs.getString(3),rs.getString(2));
            tread[i].start();
        }

but the problem is that this isnt working. 但问题是这不起作用。 i need a possibility to create for each row in the table a new thread. 我需要有可能为表中的每一行创建一个新线程。 dose anyone have an idea how to do that 剂量任何人都知道如何做到这一点

thanks and greetings 谢谢和问候

You need a dynamically growing container for a set of unknown size - a List , for example: 对于一组未知大小,您需要一个动态增长的容器 - 例如: List

List<Thread> threads = new ArrayList<Thread>();
while (rs.next()) {
    Thread tread  = new Savescreenshots(rs.getString(1),rs.getString(3),rs.getString(2));
    tread.start();
    threads.add(thread);
}

At this point, all Thread objects that your program created and started are elements of the threads list. 此时,程序创建和启动的所有Thread对象都是threads列表的元素。 You can enumerate them and do whatever else you were planning to do with them (eg wait for them to finish): 你可以枚举它们并做任何你打算用它们做的事情(例如等待它们完成):

for (Thread thread : threads) {
    thread.join();
}

您的想法听起来很疯狂,但您可以做的是使用Java中的SQL功能,找出您当前有多少行,然后使用该数字创建您的线程。

try using just simple variable say t instead of array tread[i]. 尝试使用简单的变量说t而不是数组胎面[i]。

Also, creating a new thread for every row might fill out memory if number of rows is large. 此外,如果行数很大,则为每行创建新线程可能会填充内存。

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

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