You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
1.6 KiB
68 lines
1.6 KiB
package com.fr.design.worker; |
|
|
|
import com.fr.log.FineLoggerFactory; |
|
|
|
import javax.swing.SwingWorker; |
|
import java.util.concurrent.Callable; |
|
import java.util.concurrent.TimeUnit; |
|
import java.util.concurrent.TimeoutException; |
|
|
|
/** |
|
* 通用的Worker |
|
* |
|
* @author Destiny.Lin |
|
* @since 11.0 |
|
* Created on 2024/1/8 |
|
*/ |
|
public class DefaultWorker<T> extends SwingWorker<T, Void> { |
|
|
|
private static final int TIME_OUT = 50; |
|
private boolean slowly = false; |
|
private final Callable<T> doInBackground; |
|
private T result; |
|
|
|
public DefaultWorker(Callable<T> doInBackground) { |
|
this.doInBackground = doInBackground; |
|
} |
|
@Override |
|
protected T doInBackground() throws Exception { |
|
return this.doInBackground.call(); |
|
} |
|
|
|
@Override |
|
protected void done() { |
|
try { |
|
result = get(); |
|
if (slowly) { |
|
dealResultWhenSlowly(result); |
|
} |
|
} catch (Exception e) { |
|
throw new RuntimeException(e); |
|
} |
|
} |
|
|
|
/** |
|
* 获取结果 |
|
*/ |
|
public T getResult() { |
|
if (result != null) { |
|
return result; |
|
} |
|
try { |
|
return this.get(TIME_OUT, TimeUnit.MILLISECONDS); |
|
} catch (TimeoutException e) { |
|
slowly = true; |
|
} catch (Exception exception) { |
|
FineLoggerFactory.getLogger().error(exception.getMessage(), exception); |
|
} |
|
return null; |
|
} |
|
|
|
|
|
/** |
|
* 如果获取结果超过TIME_OUT,则通过这个方式处理后续 |
|
*/ |
|
public void dealResultWhenSlowly(T result) { |
|
|
|
} |
|
}
|
|
|