如何使用线程从另一个调用不同的函数 class

How to use threading to call different functions from another class

我有一个服务器 class 具有三种方法 start/stop/redirect。请在下面找到代码。

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();
}