gpt4 book ai didi

java - 如何使用线程调用另一个类的不同函数

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

我有一个服务器类,它具有三种方法启动/停止/重定向。请找到下面的代码。

public class Syslog
{
private static final int PORT = 519;
private static final int BUFFER_SIZE = 10000;
private static boolean server_status=false;


public static void startServer()
{
server_status=true;
}

public static void stopServer()
{
server_status=false;
}

public void redirectToFile(byte[] bs) throws IOException
{
String data=new String(bs);

File file = new File("C:\\audit_log.txt");

// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}

FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(data);
bw.close();

System.out.println("Done");

}

public void runServer() throws IOException
{
DatagramSocket socket = new DatagramSocket(PORT);
DatagramPacket packet = new DatagramPacket(new byte[BUFFER_SIZE],BUFFER_SIZE);

System.out.println("Receiving data from the socket and redirecting it to a file C:\\audit_log.txt");
while(server_status)
{
packet.setLength(BUFFER_SIZE);
socket.receive(packet);

System.out.printf("Got %d bytes from %s%n",packet.getLength(),packet.getSocketAddress());
System.out.write(packet.getData());

redirectToFile(packet.getData());
}

socket.close();
}

}

我有一个 junit 测试,我想在 @beforeclass 中启动服务器并在 @afterclass 中停止它。我还需要在测试执行期间调用 runServer() 。我尝试使用线程,但在实现过程中感到非常困惑。有人可以指出一种设计方法来处理这个问题吗?然后我会尝试相应地编码。

最佳答案

建议您在 runServer() 中生成一个线程。这样您就不必在 JUnit 测试中处理线程。像这样的事情:

private Thread serverThread;
IOException thrown;

public void runServer() throws IOException {
if (serverThread != null) {
throw new IOException("Server is already running");
}
serverThread = new Thread(new Runnable() {
public void run() {
DatagramSocket socket = null;
try {
socket = new DatagramSocket(PORT);
DatagramPacket packet = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE);
while (server_status) {
packet.setLength(BUFFER_SIZE);
socket.receive(packet);
System.out.write(packet.getData());
redirectToFile(packet.getData());
}
} catch (IOException e) {
thrown = e;
} finally {
serverThread = null;
if (socket != null) socket.close();
}
}
});
serverThread.start();
}

关于java - 如何使用线程调用另一个类的不同函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27978056/

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