小编典典

使用线程逐块处理文件

java

我有一个由5000个IP地址组成的arraylist。对于每个IP地址,我要执行SNMPGet请求和FTPDownload命令。我想以一种方式实现它,其中一次,前五个IP地址同时运行2个不同的线程。执行完这些IP地址后,将在这些线程上执行接下来的2个IP地址。有人可以帮忙吗?

在这里,连接是扩展线程的类,要实现的工作在其run()方法中编写。请帮忙。

Connection newConnection =new Connection(0);
Connection newConnection1 =new Connection(1);

for(int i = 0; i < NE_list.getRowCount(); i=i+2)
{
if(NE_list.getValueAt(i, 0).toString().equals("true")) //Some condition here for the IP Address
{

            newConnection.i=i;
            newConnection1.i=i+1;
            newConnection.runprogram();
            newConnection1.runprogram();
 }


    }

class Connection extends Thread{
int  i;
Connection(int val){
  i=val;
}
void runprogram(){
start();
}
public void run(){
//SNMP and FTP Code here for IP Address in index i of NE_list
}
}

阅读 209

收藏
2020-11-26

共1个答案

小编典典

Executor框架将最适合您的解决方案。我在这里创建了一个示例。您可以根据需要增加线程数。

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class SomeRunnable implements Runnable {
    int threadNo = -1 ;
    List<String> list = new ArrayList<String>();
    public SomeRunnable(List list, int threadNo ) {
        this.list.addAll(list);
        this.threadNo =threadNo;
    }
    @Override
    public void run() {
        for (String element : list) {
            System.out.println("By Thread:" + threadNo+", Processed Element:" +element);
        }
    }

}

public class ExecutorDemo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < 100; i++) {
            list.add("Elem:"+i);
        }
        // Divide list 
        int divideIndex = list.size()/2;
        //Create objects of Runnable
        SomeRunnable obj1 = new SomeRunnable(list.subList(0, divideIndex),1);
        SomeRunnable obj2 = new SomeRunnable(list.subList(divideIndex,list.size()),2);

        //Create fixed Thread pool, here pool of 2 thread will created
        ExecutorService pool = Executors.newFixedThreadPool(2);

        pool.execute(obj1);
        pool.execute(obj2);

        pool.shutdown();
    }

}
2020-11-26