2012-05-09 27 views
-4

我是Java窗口应用程序的新手。我需要制作一个运行脚本的Java工具。该脚本运行像- .txt file并给出了下面的输出:如何从线程返回多个值以及如何处理此值

line 1 
line 2 
line 3 
and so on.... 

我需要Java程序来完成以下步骤:

  1. 检查各行语法的正确与否
  2. 如果行正确的,使一个byte []与此线
  3. 过程byte []数组

我想在这里使用线程浓度。我想要该子线程句柄1和2进程并将主线程返回byte[]。主程序然后会处理这个字节数组。

我能够使用线程,但返回值有问题。一个线程如何将每行返回byte[]到主线程?主线程如何以同步方式接收这个byte[]数组?

+0

会有只有一个文本文件? –

+0

yes只有一个没有行的文本文件,每行代表一个命令,如果编写得很好,我需要提取它 – Arjun

+2

然后通过多个线程访问一个文件将不是一个好的多线程解决方案。 –

回答

0

从线程返回值的最简单方法是使用ExecutorServiceFuture类。您可以根据需要将任意数量的作业提交到线程池。您还可以添加更多线程或为每个作业分配线程。请参阅Executors中的其他方法。

例如:

// create a thread pool 
ExecutorService threadPool = Executors.newFixedThreadPool(2); 
// submit a job to the thread pool maybe with the script name to run 
Future<byte[]> future1 = threadPool.submit(new MyCallable("scriptFile1.txt")); 
// waits for the task to finish, get the result from the job, this may throw 
byte[] result = future1.get(); 

public class MyCallable implements Callable<byte[]> { 
    private String fileName; 
    public MyCallable(String fileName) { 
     this.fileName = fileName; 
    } 
    public byte[] call() { 
     // run the script 
     // process the results into the byte array 
     return someByteArray; 
    } 
}); 
+0

感谢您的时间灰色......它看起来很难....我要试试这个。我希望........ – Arjun

+0

在正常的线程中,我做了一个线程类的对象,并在点击或从任何地方按钮上调用obj.start()。你的意思是说我应该使用公共类MyCallable implements Callable 而不是public class mythread extends Thread {}对不对?有一件事更多 - 如果我的文件包含10行意味着我需要一个接一个地返回10个字节[],但它似乎只会返回一次。给我一些提示,我如何可以逐行处理一行,并为每一行返回byte [],我想实现like- as sooon线程返回值,立即执行一些代码行并使用返回值 – Arjun

+0

Yes ExecutorService '为你处理线程。所有你需要的是一个'Callable'。 – Gray