有一些关于使用 LibGDX 中的资源异步加载纹理的讨论。据我所知 LibGDX 使用 2 种方法(异步和同步)来加载数据。如果它依赖于使用 OpenGL 函数,它会使用具有 GL 上下文的主线程并同步执行,否则异步执行。
我需要异步加载和处理纹理。加载速度很快。不幸的是,我不能对流程说同样的话。这个过程是纹理的一些变形,需要很多时间。因此,我尝试将线程分开,如下所示:
public void load(final String filename){
if(callback!=null && !isLoading){
//WE NEED TO USE THIS FUNC AS DESCRIBED IN LIBGDX MANUAL
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
//SIMULATE HEAVY PROCESS
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(callback!=null){
callback.onComplete(filename);
}
}
});
}
//JAVA CLASS HAS THE SAME BEHAVIOUR
new Thread(new Runnable() {
@Override
public void run() {
//SIMULATE HEAVY PROCESS
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(callback!=null){
callback.onComplete(filename);
}
}
}).run();
该线程使主线程停止 10 秒。为什么?所以,我可以假设这个线程在主线程内执行。重点是什么? LibGDX 中可以分离线程吗?如何在2个线程之间共享GL上下文? 顺便我找到了example ,但它不适合 LibGDX。
还有一个有趣的类(class)here其中说:
/*
To handle an event you will typically subclass GLSurfaceView and override the
appropriate method, just as you would with any other View. However, when handling
the event, you may need to communicate with the Renderer object
that's running in the rendering thread. You can do this using any
standard Java cross-thread communication mechanism. In addition,
one relatively easy way to communicate with your renderer is
to call
For example:
*/
class MyGLSurfaceView extends GLSurfaceView {
private MyRenderer mMyRenderer;
public void start() {
mMyRenderer = ...;
setRenderer(mMyRenderer);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
queueEvent(new Runnable() {
// This method will be called on the rendering
// thread:
public void run() {
mMyRenderer.handleDpadCenter();
}});
return true;
}
return super.onKeyDown(keyCode, event);
}
}
最佳答案
您无法在线程之间共享 GL 上下文。
Gdx.app.postRunnable() 不会启动新线程,它只是将 Runnable 添加到主线程,然后在下一帧中处理该线程。这就是你的主线程停止的原因。
关于java - LibGDX - 异步加载和处理纹理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30748864/