JS need same thread
This commit is contained in:
parent
08aa6c6b85
commit
5db0220ab5
|
|
@ -3,23 +3,52 @@ package com.github.catvod.spider;
|
|||
import android.content.Context;
|
||||
|
||||
import com.github.catvod.crawler.Spider;
|
||||
import com.github.catvod.crawler.SpiderDebug;
|
||||
import com.whl.quickjs.android.QuickJSLoader;
|
||||
import com.whl.quickjs.wrapper.QuickJSContext;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
public class JSDemo extends Spider {
|
||||
|
||||
private ExecutorService executor;
|
||||
private QuickJSContext ctx;
|
||||
|
||||
private void submit(Runnable runnable) {
|
||||
executor.submit(runnable);
|
||||
}
|
||||
|
||||
private <T> Future<T> submit(Callable<T> callable) {
|
||||
return executor.submit(callable);
|
||||
}
|
||||
|
||||
private void initJS() {
|
||||
if (ctx != null) return;
|
||||
ctx = QuickJSContext.create();
|
||||
QuickJSLoader.initConsoleLog(ctx);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(Context context, String extend) {
|
||||
ctx = QuickJSContext.create();
|
||||
ctx.evaluate("var text = 'Hello QuickJS';");
|
||||
String text = ctx.getGlobalObject().getString("text");
|
||||
SpiderDebug.log(text);
|
||||
this.executor = Executors.newSingleThreadExecutor();
|
||||
submit(this::initJS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String homeContent(boolean filter) throws Exception {
|
||||
return submit(() -> {
|
||||
ctx.evaluate("var text = 'homeContent';");
|
||||
return ctx.getGlobalObject().getString("text");
|
||||
}).get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
ctx.destroy();
|
||||
submit(() -> {
|
||||
executor.shutdownNow();
|
||||
ctx.destroy();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue