简体   繁体   English

从另一个线程中的对象运行方法

[英]Running a method from an object in another Thread

I have LibGDX Application in which I paint and a Thread for Client or Server. 我在其中绘画的LibGDX应用程序中有一个用于客户端或服务器的线程。 Connections are done using Kryonet. 使用Kryonet完成连接。 When your opponent creates does something a message is recieved linke so: 当您的对手创建某项操作时,会收到一条消息,链接如下:

public void received(Connection con, Object object) {

                            TroopMessage tm = (TroopMessage)object;                         
                            fortress.map.addSoldier(tm.kind, true);
                            System.out.println("recieved");

                            connection = con;
}

When this callback is called (and it is correctly) I get "No OpenGL context found in the current thread". 调用此回调时(正确),我得到“在当前线程中找不到OpenGL上下文”。 I think it is looking for the object fortress within the MyClient Thread. 我认为这是在MyClient线程中寻找对象要塞。 I want to call to fortress.map.addSoldier which refers to an object currently existing in another thread. 我想调用totress.map.addSoldier,它引用当前在另一个线程中存在的对象。

public class Fortress extends Game implements ApplicationListener{
    private OrthographicCamera camera;
    private SpriteBatch batcher;

    public static MyServer server;
    public static MyClient client;

    public static Map map;
[....]

How can I call the method in from another thread? 如何从另一个线程调用该方法?

thanks in advance 提前致谢

In Libgdx you can use Gdx.app.postRunnable(Runnable r) to ask the main OpenGL-context-having render thread to run some code. 在Libgdx中,您可以使用Gdx.app.postRunnable(Runnable r)要求具有OpenGL上下文的主渲染线程运行一些代码。 See the Libgdx wiki about application threading here: https://code.google.com/p/libgdx/wiki/ApplicationThreading 在此处查看有关应用程序线程的Libgdx Wiki: https : //code.google.com/p/libgdx/wiki/ApplicationThreading

As the comments point out, generally Java objects are not "owned" by a thread. 正如注释所指出的,通常Java对象不是线程“拥有”的。 The "OpenGL context" is something of an exception to this, as only one thread is allowed to make changes to the OpenGL state. “ OpenGL上下文”是一个例外,因为只允许一个线程更改OpenGL状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM