gpt4 book ai didi

Java多线程端口扫描器

转载 作者:行者123 更新时间:2023-12-01 12:30:03 26 4
gpt4 key购买 nike

努力让它比现在跑得更快。它非常慢,线程似乎不同时进行,无法弄清楚。如果有人可以帮助描述我的问题出在哪里,以便我可以找出如何让它运行得更快,我将非常感激,非常感谢!

package infoGrabber;

import java.awt.List;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

public class infoMain {

public static int port;

@SuppressWarnings("resource")
public static void main(String[] args) {
System.out.println("What host do you want to lookup?: ");
Scanner userEntry = new Scanner(System.in);
String host = userEntry.nextLine();

try {
startThreads(host);
} catch (InterruptedException e) {
e.printStackTrace();
}

}

private static void startThreads(String host) throws InterruptedException {
int numThreads = 10;
int count = 10;
Thread[] threads = new Thread[numThreads];
System.out.println("Creating threads");
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Runner(host, count));
threads[i].start();
threads[i].join();
}
System.out.println("Done");
}
}

class Runner implements Runnable {
static int port;
private final String host;
private final int count;
infoMain main = new infoMain();

public Runner(String host, int count) {
this.host = host;
this.count = count;
}

public void run() {
for (int port = 0; port < 2000; port++) {
// System.out.println(name + "=" + i + "\n");
Socket socket;
try {
socket = new Socket(host, port);// Attempt to establish a socket on port i.
// If no IOException thrown, there must
// be a service running on the port.
System.out.println("Port " + port + " is open.");
socket.close();
} catch (IOException ioEx) {
System.out.println("Port " + port + " is not open.");
}// No server on this port
}
Thread.yield();
}
}

最佳答案

您不会在线程之间分配工作。相反,您为每个线程分配相同数量的工作,就像在顺序程序中分配给主线程一样。您应该在线程之间分配工作以提高执行速度。

你的循环应该类似于:

 for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Runner(host, count * NUMBER_OF_PORTS_PER_THREAD));
threads[i].start();

}

// Join threads after you created them
// All credits for @biziclop for spotting this
for (int i = 0; i < threads.length; i++) {
threads[i].join();
}

您的可运行代码应该类似于:

class Runner implements Runnable {

final private int startPort;

public Runner(String host, int startPort) {
this.host = host;
this.startPort = startPort;
}

public void run() {
for (int port = startPort; port <= NUMBER_OF_PORTS_PER_THREAD + startPort; port++) {
...
}
}

其中 NUMBER_OF_PORTS_PER_THREAD 应等于 200,以使用 10 个线程扫描 2000 个端口。

关于Java多线程端口扫描器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26004337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com