gurkenmaster1000
gurkenmaster1000

Reputation: 33

Sharing objects between multiple threads in a game

Programming language: JAVA / Android

Thread "Structure"

Main Thread (starts other treads)

---(multiple attributes)

---AI thread

---TouchListener thread

---Scripting thread

---Render thread

Description

An example for an attribute would be an actor that is instructed by the scritping thread; has it's route calculated by the AI thread and the 3D coordinates changed by the renderer.

All the threads are NOT private inner classes with access to the attributes, instead they are simple classes which implement Runnable

Question

How to share objects (the attributes) between those endlessly running threads? Every thread must have access to all the resources of the main thread. (the question is not about how to syncronize them, I know "syncronized" and the concept of locks already)

Upvotes: 3

Views: 550

Answers (3)

Andrew Clark
Andrew Clark

Reputation: 208435

One option would be to make your "attributes" static variables in a class to use them globally:

Example from that answer:

public class Global {

public static int a;
public static int b;
}

now you can access a and b from anywhere by calling

Global.a;

Global.b;

Upvotes: 0

Aubin
Aubin

Reputation: 14853

You may create a class SimulationModel which is instantiated by Main thread/class and provided to others by a setter or by their constructor.

This class contains all the data and own the locks to maintain consistency.

The logic about data manipulation may take place here too.

Upvotes: 1

John B
John B

Reputation: 32949

If you are not asking about making access to the objects thread-safe, are you just asking how to have access to them in the other threads? If so, just pass them in to those runnable objects via a constructor.

Upvotes: 0

Related Questions