Java 同时使用超时和信号量进行线程阻塞
我有一个方法可以运行,它可以连接到服务器,当服务器出现故障时,它会一直等到收到服务器再次启动的消息。然而,整个方法应该有一个超时,如果超时,方法应该中断并返回错误日志Java 同时使用超时和信号量进行线程阻塞,java,multithreading,concurrency,semaphore,Java,Multithreading,Concurrency,Semaphore,我有一个方法可以运行,它可以连接到服务器,当服务器出现故障时,它会一直等到收到服务器再次启动的消息。然而,整个方法应该有一个超时,如果超时,方法应该中断并返回错误日志 private Semaphore sem = new Semaphore(0); private TimeUnit unit = TimeUnit.MILLISECONDS; public String some_method(Object params, long timeout, TimeUnit unit) {
private Semaphore sem = new Semaphore(0);
private TimeUnit unit = TimeUnit.MILLISECONDS;
public String some_method(Object params, long timeout, TimeUnit unit) {
long time = 0;
while(time < timeout) { // not sure about timeout method
try {
//some task that is prone to ServerConnectException
return; // returns value and exits
} catch(ServerConnectException ex) {
sem.acquire();
} catch(InterruptedException uhoh) {
System.out.println("uhoh, thread interrupted");
}
// increment time somehow
}
sem.release();
return null; // a message of task incompletion
}
私有信号量sem=新信号量(0);
专用时间单位=时间单位。毫秒;
公共字符串some_方法(对象参数、长超时、时间单位){
长时间=0;
while(time
- 我曾考虑运行一个包含信号量的线程,如果出现服务器故障问题,该线程将阻塞线程,但我似乎无法组织线程,使其包含信号量,而由方法本身包含
谢谢 在这里,信号量似乎不是正确的并发原语,因为您实际上不需要一个用于锁定的实用程序,而是一个帮助您协调线程间通信的实用程序 如果需要传递值流,通常会使用阻塞队列,但如果需要传递单个值,则使用CountDownLatch和变量即可。例如(未经测试):
我猜您忘记了问题Fixed,danke,因为创建一个线程实例来调用一个方法应该不会影响方法本身的设计,所以不应该真正影响您的API。
public String requestWithRetry(final Object params, long timeout, TimeUnit unit) throws InterruptedException {
String[] result = new String[1];
CountDownLatch latch = new CountDownLatch(1);
Thread t = new Thread(new Runnable() {
public void run() {
while (true) {
try {
result[0] = request(params);
latch.countDown();
return;
}
catch(OtherException oe) {
// ignore and retry
}
catch(InterruptedException ie) {
// task was cancelled; terminate thread
return;
}
}
}
});
t.start();
try {
if (!latch.await(timeout, unit)) {
t.interrupt(); // cancel the background task if timed out
}
// note that this returns null if timed out
return result[0];
}
catch(InterruptedException ie) {
t.interrupt(); // cancel the background task
throw ie;
}
}
private String request(Object params) throws OtherException, InterruptedException {
// should handle interruption to cancel this operation
return null;
}