简体   繁体   English

如何在Web应用程序中调用Java并发线程

[英]How to call Java concurrent threads in web application

Am working on some web application and i got struck in some where and i need your help. 我正在某个Web应用程序上工作,我在某些地方感到震惊,我需要您的帮助。 I developed one java web application using struts framworks. 我使用struts framworks开发了一个Java Web应用程序。 This application takes source folder from user and copied in unique directory inside server and it will execute batch process on each source folder and batch will write logs on inside respective folder. 此应用程序从用户那里获取源文件夹并复制到服务器内部的唯一目录中,它将在每个源文件夹上执行批处理,并且批处理将在相应文件夹内写入日志。 Uploading and copying source folder is working fine but real issue am facing is executing batch concurrently. 上载和复制源文件夹工作正常,但真正面临的问题是同时执行批处理。 When one user upload source folder and start batch execution and same time another user also upload source folder and start batch and i need to know when first user batch completes and second user completes.How to track concurrent threads completed or not.Am using Executor executor= Executors.newCachedThreadPool(); 当一个用户上传源文件夹并开始执行批处理,而另一个用户同时上传源文件夹并开始批处理时,我需要知道第一个用户批处理何时完成而第二个用户完成了。如何跟踪并发线程是否完成。使用Executor executor = Executors.newCachedThreadPool(); Please find below code 请找到下面的代码

 private class BackgroundTask extends SwingWorker<Integer, String> {
        String srcpath;
 String log;
         BackgroundTask(String path)
         {
             this.srcpath=path;
         }
            private int status;

            public BackgroundTask() {

            }
            @Override
            protected Integer doInBackground() {
                try {
                    final File batchFile = new File("D://chetan//bin//runner.bat");
                 ProcessBuilder builder = new ProcessBuilder();
                  builder.directory(new File(srcpath));
                  String[] cmd = { "cmd", "/c",batchFile.getAbsolutePath(),"-X"};

                  for (int x = 0; x < cmd.length; x++) {
                        System.out.println("Command :" + cmd[x]);   

                    }
                     builder.command(cmd);

                     Process process;
                     process = builder.start();
                     InputStream is1 = process.getInputStream();
                        InputStreamReader isr = new InputStreamReader(is1);
                        BufferedReader br = new BufferedReader(isr);
                        String line;
                     File logfile;
                     File logpath=new File(srcpath+File.separator+"LOG");
                     if(logpath.isDirectory())
                     {
                          logfile=new File(logpath+File.separator+"runner.log");

                     }
                     else
                     {
                         logpath.mkdir();
                         logfile=new File(logpath+File.separator+"runner.log");
                     }
                     logfile.createNewFile();
                     while ((line = br.readLine()) != null) {                           
                            //appendText(line);                     
                         log+=line+"\n";                    
                     }
                     FileUtils.writeStringToFile(logfile,log);           

                    process.getInputStream().close();
                    process.getOutputStream().close();
                    process.getErrorStream().close();
                    process.destroy();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return status;
            }
            @Override
            protected void process(java.util.List<String> messages) {
               // statusLabel.setText((this.getState()).toString());               
            }

            @Override
            protected void done() {

            }

        }

Second Class 二等

public class RunnerAnalysisAction extends ActionSupport implements SessionAware {
 private BackgroundTask backgroundTask;

 public String execute() {
  String projectRoot="D:\\Sample_DemoProjects\\DEMO_375530\\";
 backgroundTask = new BackgroundTask(projectRoot+ProjectName);
 Executor executor= Executors.newCachedThreadPool();
 executor.execute(backgroundTask);
return SUCCESS;  
 }
}

The above code working fine and creates log file in corresponding source folder but i need to know when the batch will completes the task because once batch completes its task this application will trigger email to user with log.How to know the particular task completed or not.Please provide some sample code.Thanks. 上面的代码可以正常工作并在相应的源文件夹中创建日志文件,但是我需要知道批处理何时完成任务,因为一旦批处理完成其任务,该应用程序将触发带有日志的电子邮件给用户。如何知道特定任务是否完成请提供一些示例代码。

You didn't specify the nature of your web application. 您没有指定Web应用程序的性质。 If it is not clustered (running single instance) then keep a static variable (or an instance variable inside ActionServlet , which is singleton ). 如果它不是集群的(运行单个实例),则保留一个静态变量(或ActionServlet内的一个实例变量,它是singleton )。 Set this variable to "true" when a thread (worker task) from previous user is already running and reset to false when thread completes. 当上一个用户的线程(工人任务)已经在运行时,将该变量设置为“ true”,并在线程完成时将其重置为false。 Use this flag to check whether another thread (from another user) can run- true means can't run, false means can run. 使用此标志检查另一个线程(来自另一个用户)是否可以运行-真意味着不能运行,假意味着可以运行。 Alternatively define the ExecutorService as a shared (static) instance and then make it a SingleThreaded pool and submit workers to it. 或者,将ExecutorService定义为共享(静态)实例,然后使其成为SingleThreaded池并向其提交工作程序。 Hope you got the idea. 希望你有主意。

To track concurrent threads I have used java.util.concurrent.Future . 为了跟踪并发线程,我使用了java.util.concurrent.Future A Future represents the result of an asynchronous computation. Future表示异步计算的结果。 Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. 提供了一些方法来检查计算是否完成,等待其完成以及检索计算结果。 The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. 只有在计算完成后才可以使用get方法检索结果,必要时将其阻塞,直到准备就绪为止。

You can try this complete example 您可以尝试这个完整的例子

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

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