我想發送到「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();
}
}
}
}
}
我知道這可能是你看過的最可怕的一段代碼,但正在做我想要的東西,如果你能給我一些指導,說明我該如何以正確的方式完成這一點,那將是非常棒的。
感謝您的所有偉大的裝運通知
感謝您的回答 –