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

时间:2015-01-16 05:53:39

标签: java multithreading junit

我有一个服务器类有三个方法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()。我尝试使用线程但在实现过程中确实很困惑。有人可以指出一种设计方法来处理这个问题。然后我会尝试编码。

1 个答案:

答案 0 :(得分:1)

建议您在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();
}