如何使用线程从另一个类调用不同的函数
Posted
技术标签:
【中文标题】如何使用线程从另一个类调用不同的函数【英文标题】:How to use threading to call different functions from another class 【发布时间】:2015-01-16 05:53:39 【问题描述】:我有一个服务器类,它具有三种方法启动/停止/重定向。请在下面找到代码。
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】:建议你在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();
【讨论】:
谢谢。我可以使用上面的代码稍作修改。 这对你有用吗?如果您需要更多信息以获得完整答案,请告诉我。我想为你的问题的正确答案获得荣誉:) 见Accepting Answers: How does it work?以上是关于如何使用线程从另一个类调用不同的函数的主要内容,如果未能解决你的问题,请参考以下文章