我想向“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();
}
}
}
}
}
我知道这可能是你看过的最糟糕的一段代码,但它正是我想要的,如果你能给我一些指导,告诉我应该如何以正确的方式完成这件事,那就太好了。
非常感谢您提供的所有重要建议