我想讓程序讀取文件中的條目,收集數組中的10個etnries,然後以此數組作爲參數提交一個線程。似乎一切都在這一點上的邏輯是正確的,但在運行時我收到絕對不同影響的結果:如何正確地將參數傳遞給fixedthreadpool,並控制線程執行?
代碼:
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);
}
}
}
當我運行此我得到不同的結果,無法理解爲什麼:
[email protected] ~/java $ javac headScanner.java
[email protected] ~/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
[email protected] ~/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
[email protected] ~/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
對不起,愚蠢的問題,我正確地將參數傳遞給runnable類? 我想這樣的:
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
可能傳遞ARGS的比較正確的做法,但我想不出任何Google。 感謝您的任何幫助
您是不是使用IDE? –
我使用崇高... –
嘗試Eclipse,Netbeans或IntelliJ。這將大大幫助你intellisense和喜歡。 –