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 android.content.Context;
|
||||||
|
|
||||||
import com.github.catvod.crawler.Spider;
|
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 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 {
|
public class JSDemo extends Spider {
|
||||||
|
|
||||||
|
private ExecutorService executor;
|
||||||
private QuickJSContext ctx;
|
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
|
@Override
|
||||||
public void init(Context context, String extend) {
|
public void init(Context context, String extend) {
|
||||||
ctx = QuickJSContext.create();
|
this.executor = Executors.newSingleThreadExecutor();
|
||||||
ctx.evaluate("var text = 'Hello QuickJS';");
|
submit(this::initJS);
|
||||||
String text = ctx.getGlobalObject().getString("text");
|
}
|
||||||
SpiderDebug.log(text);
|
|
||||||
|
@Override
|
||||||
|
public String homeContent(boolean filter) throws Exception {
|
||||||
|
return submit(() -> {
|
||||||
|
ctx.evaluate("var text = 'homeContent';");
|
||||||
|
return ctx.getGlobalObject().getString("text");
|
||||||
|
}).get();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void destroy() {
|
public void destroy() {
|
||||||
|
submit(() -> {
|
||||||
|
executor.shutdownNow();
|
||||||
ctx.destroy();
|
ctx.destroy();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue