2012-10-11 80 views
2

我想發送到「test.com」一個從0到100的請求,我的代碼會每隔一秒發送一個請求...這樣程序將需要100秒的順序去完成。Java多線程多請求方法

我想要做的是設置10個線程在同一時間運行,使線程1從(0,10);線程2從(10,20)...等等,這樣程序應該只需要10秒鐘左右才能完成,這是可能的嗎?如何能夠實現它?

import java.io.InputStreamReader; 
import org.apache.commons.httpclient.HttpClient; 
import org.apache.commons.httpclient.methods.PostMethod; 

public class Palomo implements Runnable { 
    String url = "http://test.com"; 
    HttpClient client = null; 
    PostMethod method = null; 
    BufferedReader br = null; 
    String contents = null; 

    public void run() { 
     for (int i = 0; i <= 100; i++) { 
      synchronized (this) { 
       doPost(i); 
      } 
         try { 
     Thread.sleep(1000); 
     } catch (InterruptedException e) { 
     e.printStackTrace(); 
     } 
     } 
    } 

    public void doPost(int i) { 
     try { 
      client = new HttpClient(); 
      method = new PostMethod(url); 

      this.method.addParameter("myPostRequest", Integer.toString(i)); 

      client.executeMethod(method); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      method.releaseConnection(); 
     } 
    } 

    public static void main(String[] args) { 
     new Thread(new Palomo()).start(); 
    } 
} 

非常感謝!

編輯

讀你給我的指示,我創造了這個可怕的怪物......

import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 

public class SimpExec { 
    public static void main(String args[]) { 

     ExecutorService es = Executors.newFixedThreadPool(4); 

     es.execute(new MyThread("A")); 
     es.execute(new MyThread("B")); 
     es.execute(new MyThread("C")); 
     es.execute(new MyThread("D")); 

     es.shutdown(); 
    } 
} 

class MyThread implements Runnable { 
    String name; 

    MyThread(String n) { 
     name = n; 
     new Thread(this); 
    } 

    public void run() { 
     if (name=="A"){ 
      for (int i=1;i<=10;i++){ 
       System.out.println(i); 
       try { 
        Thread.sleep(1000); 
       } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
     } 
     if (name=="B"){ 
      for (int i=10;i<=20;i++){ 
       System.out.println(i); 
       try { 
        Thread.sleep(1000); 
       } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
     } 
     if (name=="C"){ 
      for (int i=20;i<=30;i++){ 
       System.out.println(i); 
       try { 
        Thread.sleep(1000); 
       } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
     } 
     if (name=="D"){ 
      for (int i=30;i<=40;i++){ 
       System.out.println(i); 
       try { 
        Thread.sleep(1000); 
       } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 
} 

我知道這可能是你看過的最可怕的一段代碼,但正在做我想要的東西,如果你能給我一些指導,說明我該如何以正確的方式完成這一點,那將是非常棒的。

感謝您的所有偉大的裝運通知

回答

5

很多你應該看看ExecutorService它已經建立,以實現這樣的事情。

您可以使用Executors.newFixedThreadPool(10);創建10個線程池,然後提交您想要執行的任務(Runnable)。池負責調度線程之間的任務。

+0

感謝您的回答 –

0

爲什麼不縮短PostRequest之間的時間。使用線程會產生相同的影響,因爲發送之間的時間較短。你會使用這個線程改變該帖子被髮送到

1,11,21,31,41 ...... 2,12,22,32的順序完成的唯一的事,...

使用

Thread.CurrentThread.Sleep(100) 

降低時間在主應用程序發送之間。

此外,您可能會遇到麻煩,讓多個線程訪問相同的HTTPClient。即使你同步了acces,發送過程也是串行的,因爲httpclient一次只能發送1個請求。

0

要添加其他評論,建議使用ExecutorService(這是一個很好的解決方案)
每個提交的Runnable對象都應該有處理請求的範圍。
。你應該考慮讓類延伸Runnable。
它的代碼可以loook像 -

public class RangedPosts extends Runnable { 
    private int start; 
    private int end; 
    public RangedPosts(int start,int end) { 
     this.start = start; 
     this.end = end; 
    } 

    public void run() { 
     //Perform here a loop from start to end 
    } 
} 

然後使用應該是for循環中,創建RangePosts 10點可運行的對象,使它們的範圍內定義(開始和結束)

0

我做了類似的事情,我會分享我的第一個POC,因爲它感覺很好分享。

package test; 

import java.io.BufferedReader; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.URL; 

public class ThreadCreater { 

    // use getShape method to get object of type shape 
    public Thread threadRunner(int start, int end, int threadCount, String url) { 
    Thread thread = null; 
    int tempEnd = 0; 
    for (int i = 0; i <= end; i = i + 10) { 
     start = i; 
     tempEnd = i + 10; 
     thread = getThread(start, tempEnd, threadCount, url); 
     thread.start(); 
    } 

    return null; 
    } 

    public static Thread getThread(int start, int end, int threadCount, String url) { 
    Thread thread = new Thread() { 
     public void run() { 
     try { 
      sendGET(start, end, url); 

     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     } 

     private void sendGET(int start, int end, String url) throws Exception { 
     url += "start=" + start + "&end=" + end; 
     URL obj = new URL(url); 
     // Send post request 
     HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 

     // basic reuqest header to simulate a browser request 
     con.setRequestMethod("GET"); 
     con.setRequestProperty("User-Agent", 
      "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/51.0"); 
     con.setRequestProperty("Upgrade-Insecure-Requests", "1"); 
     con.setRequestProperty("Connection", "keep-alive"); 
     con.setDoOutput(true); 

     // reading the HTML output of the POST HTTP request 
     BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
     String inputLine; 
     while ((inputLine = in.readLine()) != null) 
      System.out.println(inputLine); 
     in.close(); 
     } 
    }; 
    return thread; 
    } 

    public static void main(String[] args) { 
    ThreadCreater obj = new ThreadCreater(); 
    int start = 0; 
    int end = 100; 
    int threadCount = 10; 
    String url = "http://iseebug.com/test.php?"; 

    obj.threadRunner(start, end, threadCount, url); 
    } 

} 

簡單test.php的代碼下面

<?php 
/** 
* Created by PhpStorm. 
* User: polo 
* Date: 02-04-2017 
* Time: 22:28 
*/ 


$q1 = isset($_GET['start']) ? $_GET['start'] : 'fakeMIP'; 
$q2 = isset($_GET['end']) ? $_GET['end'] : 'fakeMIP'; 


if($q1>=0&&$q2<=10){ 
echo $q2; 
}elseif ($q1>=10&&$q2<=20){ 
    echo $q2; 
}elseif ($q1>=20&&$q2<=30){ 
    echo $q2; 
}elseif ($q1>=30&&$q2<=40){ 
    echo $q2; 
}elseif ($q1>=40&&$q2<=50){ 
    echo $q2; 
}elseif ($q1>=50&&$q2<=60){ 
    echo $q2; 
}elseif ($q1>=60&&$q2<=70){ 
    echo $q2; 
}elseif ($q1>=70&&$q2<=80){ 
    echo $q2; 
}elseif ($q1>=80&&$q2<=90){ 
    echo $q2; 
}elseif ($q1>=90&&$q2<=100){ 
    echo $q2; 
} 

好運。

但我更喜歡java的ExecutorService的高使用率,有限的需求,你可以去基本的線程。

請幫我一下。

+0

我創建了很多web自動化應用程序和垃圾郵件工具:) – Vaibs