Java多线程多请求方法

时间:2012-10-11 08:13:49

标签: java multithreading concurrency http-post

我想向“test.com”发送一个从0到100的请求,我的代码将每秒发送一次请求......这样程序将需要100秒才能完成。

我想要做的是设置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 个答案:

答案 0 :(得分:5)

你应该看一下为实现这类目的而创建的ExecutorService

您可以使用Executors.newFixedThreadPool(10);创建10个线程的池,然后提交要执行的任务(Runnable)。该池负责在线程之间调度任务。

答案 1 :(得分:4)

您可以使用Executors.newFixedThreadPool(10)创建一个Executor,并使用它将每个请求作为自己的Runnable执行。

答案 2 :(得分:0)

为什么不缩小PostRequest之间的时间。使用线程会产生相同的影响,因为发送之间的时间较短。通过使用线程来改变帖子发送到的顺序

,你唯一能做到的就是

1,11,21,31,41 ...... 2,12,22,32,......

使用

Thread.CurrentThread.Sleep(100)

降低主应用程序中发送之间的时间。

此外,您可以通过让多个线程访问同一个HTTPClient来遇到麻烦。即使如果你同步访问,发送过程也是串行的,因为httpclient一次只能发送1个请求。

答案 3 :(得分:0)

要添加其他注释,建议使用ExecutorService(这是一个很好的解决方案)
每个提交的Runnable对象应该具有要处理的请求范围。
。你应该考虑让课程扩展Runnable。
它的代码可以像 -

一样
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循环,创建10个RangePosts的可运行对象,并为它们传递范围定义(开始和结束)

答案 4 :(得分: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用于高使用率,对于有限的要求,你可以选择基本的线程。

请帮助我。

相关问题