How to share objects among threads?
there are several similar questions . But my question is basic and not specific to a problem . I want a basic code example of how to do that . Here is the code I am working on
Controller c = new Controller(....) ;
if(.... ) //manager
{
if (jRadioButton1.isSelected())
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MyGUI().setVisible(true);//I want to pa开发者_JAVA技巧ss object c to MyGUI Thread
}
});
}
You don't need to do anything special to share objects between threads, any thread can access any object.
However, if you want to access an object safely from multiple threads, you need to be careful. Either the object's methods must be thread-safe, or you need to synchronize access to the object.
Hope this helps.
In your example, make Controller c
final and then simply pass it into your GUI via the constructor or a setter method. For example:
final Controller c = new Controller(....) ;
if(.... ) //manager
{
if (jRadioButton1.isSelected())
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
MyGUI gui = new MyGUI(c);//pass object c to MyGUI Thread via constructor
// gui.setController(c); //or you could have a setter method
gui.setVisible(true);
}
ok well to basically answer it..
Notice the change final and constructor of MyGUI
final Controller c = new Controller(....) ;
if(.... ) //manager
{
if (jRadioButton1.isSelected())
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MyGUI(c).setVisible(true);//I want to pass object c to MyGUI Thread
}
});
}
class MyGUI
{
private Controller _controller;
public MyGui(Controller c)
{
_controller = c;
}
}
It can be as easy as passing the Runnables the same reference:
final Object o = new Object();
Runnable r = new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName() + ": " + o);
}
};
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
Of course, there are important considerations if these threads will be modifying attributes of the shared object concurrently.
In your code example, you could simply change the MyGUI
constructor to take a Controller object as an argument, or provide an instance setter method.
You can share anything you want between threads : as soon as a method executing in a thread has a reference to an object, and another method in another thread has a reference to the same object, then this object is shared between the two threads.
The difficulty, in this case, is to make sure every operation done on the shared object is thread-safe (i.e. doesn't put the object in a abnormal state, and returns correct values). Immutable objects are always thread-safe. Other ones often need synchronization to be thread-safe.
精彩评论