Create multiple java threads in a while loop depending on the number of inputs

I am trying to write a java program that reads information from a database and creates a new stream for each table row. Therefore, I do not know how many threads I will need. while I have it:

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 does not work. I need the ability to create a new thread for each row in the table. dose anyone has an idea how to do this

thanks and greetings

+4
source share
3 answers

You need a dynamically growing container for a set of unknown size - List , for example:

 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 created and launched by your program are items in the threads list. You can list them and do everything you planned to do with them (for example, wait for them to complete):

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

Your idea sounds crazy, but what you can do is use the SQL functionality in Java to find out how many rows you currently have, and then use this number to create your threads.

+2
source

try using just the simple say t variable instead of the array protector [i].

In addition, creating a new thread for each line can fill the memory if the number of lines is large.

+1
source

Source: https://habr.com/ru/post/1438859/


All Articles