ファイルからエントリを読み取り、配列に 10 個のエントリを収集し、この配列を引数としてスレッドを送信するプログラムを作成しようとしています。この点ではすべてが正しいように見えますが、実行するとまったく異なる結果が得られます。
コード:
public class headScanner {
public static void main(String args[]){
Scanner our_file = null;
ArrayList<String> our_urls = new ArrayList<String>();
List<Future<String>> futures = new ArrayList<Future<String>>(10);
ArrayList<String> urls_buffer = new ArrayList<String>();
try {
our_file = new Scanner (new File ("list.txt"));
}
catch(IOException e){
System.out.println("[-] Cant open the file!");
System.exit(0);
}
System.out.println("[!] Creaing pool");
int max_threads = 50;
int urls_per_thread = 10;
ExecutorService threadPool = Executors.newFixedThreadPool(max_threads);
ArrayList<String> buffer = new ArrayList<String>();
String url;
while(our_file.hasNext()){
url = our_file.next();
if (url.length()>0){
buffer.add(url);
}
if(buffer.size()==urls_per_thread){
System.out.println("[~] Buffer is full, spawn thread...");
GoGo child = new GoGo();
child.some = buffer;
threadPool.submit(child);
buffer.clear();
}
}
threadPool.shutdown();
try {
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
}
catch (InterruptedException e ) {
}
for(Future<String> after: futures){
try {
String result = after.get();
System.out.println(result);
}
catch (InterruptedException e) {
System.out.println(e);
} catch (ExecutionException e) {
System.out.println(e);
} finally {
}
}
}
}
class GoGo implements Runnable{
ArrayList<String> some = new ArrayList<String>();
public void GoGo(ArrayList<String> received_array){
this.some = received_array;
}
public void run(){
System.out.println("I am thread");
System.out.println("Size of array received is:" + this.some.size());
for(String element: this.some){
System.out.println(element);
}
}
}
これを実行すると、異なる結果が得られます。理由がわかりません:
anybody@anymachine ~/java $ javac headScanner.java
anybody@anymachine ~/java $ java headScanner
[!] Creaing pool
[~] Buffer is full, spawn thread...
I am thread
Size of array received is:3
http://www.top-technik.com/
[~] Buffer is full, spawn thread...
I am thread
Size of array received is:0
anybody@anymachine ~/java $ java headScanner
[!] Creaing pool
[~] Buffer is full, spawn thread...
I am thread
Size of array received is:4
http://www.top-technik.com/
[~] Buffer is full, spawn thread...
I am thread
Size of array received is:0
anybody@anymachine ~/java $ java headScanner
[!] Creaing pool
[~] Buffer is full, spawn thread...
I am thread
Size of array received is:3
[~] Buffer is full, spawn thread...
I am thread
Size of array received is:0
ばかげた質問で申し訳ありませんが、実行可能なクラスに引数を正しく渡していますか? 私は次のように試しました:
threadPool.submit(new MyClass(myarray));
そして、それは私にエラーを与えました:
headScanner.java:49: error: constructor GoGo in class GoGo cannot be applied to given types;
threadPool.submit(new GoGo(buffer));
^
required: no arguments
found: ArrayList<String>
reason: actual and formal argument lists differ in length
1 error
おそらく引数を渡すより正しい方法ですが、グーグルで検索できませんでした。助けてくれてありがとう