我是一个服务器类,它监听客户端发出的请求的特定端口号。对于每个客户端,它会打开一个单独的执行线程
但问题是服务器程序在几天之后就会出现,我不得不一次又一次地重启该程序
所以,我开始编写测试用例来检查线程在完成工作后是否正常终止,这是我的代码
public class ExampleTestWithJunit extends TestCase {
public void testExampleThread() throws Throwable {
int client = 0;
while(true) {
Runnable tr1 = new GPSService(new Socket(), client++, "http://localhost/url1");
Thread thread = new Thread(tr1);
System.out.println("State: "+thread.getState());
System.out.println("Is Alive..? "+thread.isAlive());
thread.start();
}
}
private class GPSService implements Runnable {
private Socket socket;
private int clientNumber;
private String serverUrl;
public GPSService(Socket socket, int clientNumber, String serverUrl) {
this.socket = socket;
this.clientNumber = clientNumber;
this.serverUrl = serverUrl;
System.out.println("New connection with client# " + clientNumber + " at " + socket);
}
public void run() {
//My Business logic
}
}
}
从这里开始,我无法弄清楚如何检查所有线程是否正常关闭。
如果我错了任何可以随意指出的地方,请建议我实现这一目标。我已经坚持了好几天了,我希望我能在这里找到合适的答案。
答案 0 :(得分:2)
您可以使用具有预定义线程数的ExecutorService
并将您的工作提交至此ExecutorService
。
完成后,您可以尝试关闭执行程序(此操作不会暂停作业)。然后,您可以轮询执行程序以查看是否所有作业都已完成并按此操作。
示例代码:
@Test
public void test() throws Exception {
int numThreads = 10;
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
for (int i = 0; i < numThreads; i++) {
executor.execute(new GPSService());
}
executor.shutdown();
while (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
// Threads are still running
}
// All threads are completed
}