我使我的Matlab控制线程可以中断,并发现它在第一次运行时一直被中断。
这是因为GetProxyRequestCallback
内部有中断代码:
private static class GetProxyRequestCallback implements RequestCallback
{
private final Thread _requestingThread;
private volatile MatlabProxy _proxy;
public GetProxyRequestCallback()
{
_requestingThread = Thread.currentThread();
}
@Override
public void proxyCreated(MatlabProxy proxy)
{
_proxy = proxy;
_requestingThread.interrupt();
}
public MatlabProxy getProxy()
{
return _proxy;
}
}
有没有理由打断调用线程,或者这只是一个错误?
答案 0 :(得分:0)
RemoteMatlabProxyFactory.getProxy()
方法创建GetProxyRequestCallback
的实例,然后休眠,等待调用proxyCreated(...)
方法。因此,如果proxyCreated()没有中断最初创建请求的线程,则此线程将等待直到达到超时。
在我看来,这是matlabcontrol库中的一个缺陷:不应该为此目的滥用Thread.interrupt(),因为被中断的线程可能有不同的原因,不应该用于除线程信号之外的任何事情。停止。
这应该通过等待互斥锁而在matlabcontrol库中修复。
例如:
class RemoteMatlabProxyFactory implements ProxyFactory {
// [...]
@Override
public MatlabProxy getProxy() throws MatlabConnectionException {
GetProxyRequestCallback callback = new GetProxyRequestCallback();
Request request = this.requestProxy(callback);
return callback.getProxy(_options.getProxyTimeout());
}
// [...]
}
private static class GetProxyRequestCallback implements RequestCallback {
private final Object _lock = new Object();
private MatlabProxy _proxy;
@Override
public void proxyCreated(MatlabProxy proxy) {
_proxy = proxy;
_requestingThread.interrupt();
}
public MatlabProxy getProxy(long timeout) throws MatlabConnectionException {
synchronized (_lock) {
if (_proxy != null) {
return _proxy;
}
try {
_lock.wait(timeout);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new MatlabConnectionException("Thread was interrupted while waiting for MATLAB proxy", e);
}
if (_proxy == null) {
throw new MatlabConnectionException("MATLAB proxy could not be created in " + timeout + " milliseconds");
}
return _proxy;
}
}
}