使用Executor Framework演示应用程序

时间:2017-07-19 21:43:39

标签: java multithreading thread-safety executorservice

我对执行程序框架很新,所以请清楚我对下面提到的执行程序代码的疑问

任务要求:

1)我在arraylist中有(10-20k)记录,我将分配给固定的线程池。 2)我将执行代码中的所有任务。 3)我希望每个线程都会调用webservice(rest / soap) 4)获得响应后,它会将响应写在同一个文件中(假设为A)。

我已经完成了下面的虚拟代码,我知道我需要验证,但我想知道我需要在线程方面采取什么预防措施。

问题: 应该同步哪些方法? 我应该做的更多(我将处理异常,但数据安全的观点)

提前致谢。:)

import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.ThreadFactory;

/**
 * Created by so_what on 7/20/2017.
 */

public class ExecutorDemo {
    public static void main(String args[])
    {
TaskController controller=new TaskController();
        controller.startExec();
    }
}
 class TaskController
{

public TaskController(){};
    public void startExec()
    {
        //create new thread executor
        ExecutorService executorService= Executors.newFixedThreadPool(10);
        ArrayList<String>list=new ArrayList<String>();
        list.add("One");list.add("Two");//few more will come from the 
        database

        for(int i=0;i<list.size();i++)
        {
            executorService.execute(new TaskRunner(list.get(i)));
        }
        executorService.shutdown();
    }


}
class TaskRunner implements Runnable
        {
String param;

            public TaskRunner(String s) {
                this.param=s;
            }

            @Override
            public void run() {
                System.out.println("Thread is running "+ Thread.currentThread().getName());

                //need to call the webservice
                //after got the response ,need to wirte the response in the file
                //Question:Do this will fine?
                String response=webserviceCall("http://something.com/"+this.param); //will implement lets say dummy data
                writeToFile(response);






            }

            private void writeToFile(String response) {
                //Question :Do i need to synchronize this method?
                //here i will write the response to the flat file


            }
        }

0 个答案:

没有答案