我是Java多线程世界的新手,我编写了这个程序,我只是想确保它是多线程程序。在此我创建了30个由10个线程执行的任务。所以这个实现是否正确?我想你可以在我的代码中知道我在做什么。我只是生成一些随机的IP地址并将其传递给方法,并查看从方法返回后每次调用的平均时间。因此,我在跑步方法中编写了所有任务。任何建议将不胜感激。示例多线程程序
public class Testing {
public static void main(String[] args) throws InterruptedException {
int size = 10;
// create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(size);
// queue some tasks
for(int i = 0; i < 3 * size; i++) {
service.submit(new ThreadTask(i));
}
// wait for termination
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
}
class ThreadTask implements Runnable {
private int id;
public ThreadTask(int id) {
this.id = id;
}
public void run() {
System.out.println("I am task " + id);
Map<Long, Long> histgram = new HashMap<Long, Long>();
Set<String> ipNull = new HashSet<String>();
GetLocationByIpResponse resp = null;
long total = 10000;
long difference = 0;
long found = 0;
long found_country = 0;
long runs = total;
try {
long start_total = System.nanoTime();
while(runs > 0) {
String ipAddress = generateIPAddress();
long start_time = System.nanoTime();
resp = PersonalizationGeoLocationServiceClientHelper.getLocationByIp(ipAddress);
long end_time = System.nanoTime();
if(resp.getLocation() != null) {
difference = (end_time - start_time)/1000000;
} else if(resp.getLocation() == null) {
difference = 0;
}
printResult(ipAddress, resp, difference);
Long count = histgram.get(difference);
if (count != null) {
count++;
histgram.put(Long.valueOf(difference), count);
} else {
histgram.put(Long.valueOf(difference), Long.valueOf(1L));
}
runs--;
}
long end_total = System.nanoTime();
long finalTotal = (end_total - start_total)/1000000;
float avg = (float)(finalTotal)/total;
Set<Long> keys = histgram.keySet();
for (Long key : keys) {
Long value = histgram.get(key);
System.out.println("$$$GEO OPTIMIZE SVC MEASUREMENT$$$, HG data, " + key + ":" + value);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
}
这意味着这个代码在多线程程序方面是正确的。但问题可以在随机IP地址。如果我有固定名单,那么它会更好? – AKIWEB 2012-03-16 21:56:19
和'PersonalizationGeoLocationServiceClientHelper.getLocationByIp(ipAddress);''和printResult()'。你所称的一切。这是可能存在的问题之一,但还有两个问题。 – biziclop 2012-03-16 22:06:27
所以有什么建议,我怎么能让这个更准确。我可以删除'printResult()'方法。但我需要'PersonalizationGeoLocationServiceClientHelper.getLocationByIp(ipAddress);'。我想现在你知道我在做什么。 – AKIWEB 2012-03-16 22:10:06