Giả blockingMethod
chỉ ngủ đối với một số millis:
public void blockingMethod(Object input) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Giải pháp của tôi là sử dụng wait()
và synchronized
như thế này:
public void blockingMethod(final Object input, long millis) {
final Object lock = new Object();
new Thread(new Runnable() {
@Override
public void run() {
blockingMethod(input);
synchronized (lock) {
lock.notify();
}
}
}).start();
synchronized (lock) {
try {
// Wait for specific millis and release the lock.
// If blockingMethod is done during waiting time, it will wake
// me up and give me the lock, and I will finish directly.
// Otherwise, when the waiting time is over and the
// blockingMethod is still
// running, I will reacquire the lock and finish.
lock.wait(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Vì vậy, u có thể thay thế
something.blockingMethod(input)
đến
something.blockingMethod(input, 2000)
Hy vọng điều đó sẽ hữu ích.
Là một tài liệu tham khảo, hãy kiểm tra Java Concurrency in Practice bởi Brian Goetz pp 126-134, đặc biệt là phần 6.3.7 "Đặt giới hạn thời gian vào công việc" –