简体   繁体   中英

Running a method from an object in another Thread

I have LibGDX Application in which I paint and a Thread for Client or Server. Connections are done using 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". I think it is looking for the object fortress within the MyClient Thread. I want to call to fortress.map.addSoldier which refers to an object currently existing in another thread.

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. See the Libgdx wiki about application threading here: https://code.google.com/p/libgdx/wiki/ApplicationThreading

As the comments point out, generally Java objects are not "owned" by a thread. The "OpenGL context" is something of an exception to this, as only one thread is allowed to make changes to the OpenGL state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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