Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing data between threads in Java

I'm having trouble accessing data in my main thread from my new thread. I can do this just fine without threading by just using the main class getters/setters. But when I try to launch a new thread I can no longer do so.

Main Class:

public class Driver extends Application{

//create socket handlers
Runnable myNewThread = new workerThread();

//variables
private String lastMessage = "";

//getters and setters
public String setMyVariable() {
    this.MyVariable = MyVariable;
}

//main
public static void main(String[] args) {
    //launch threads
    new Thread(myNewThread).start();
}

NewThread Class:

public class workerThread implements Runnable{

public void run() {
    Driver.setMyVariable("test");
}

I get the error "Cannot resolve symbol 'setMyVariable'" in my workerThread class. As far as I can tell it's because my workerThread thread doesn't know what instance of Driver to refer to (there is only one instance, but it doesn't know that). Could someone help me understand what I'm missing? I've seen examples of declaring the new class within a function of the main class, but I'm trying to avoid this in the interest of code organization as my worker thread is going to be a bit large.

like image 800
Mr. Phil Avatar asked Oct 18 '25 11:10

Mr. Phil


1 Answers

You are calling setMyVariable("test") as if it is a static method. You need to pass an instance of Driver class to instance of workerThread.

public class workerThread implements Runnable {
  private Driver driver;

  public workerThread(Driver d, Class c) {
    this.driver = d;
    //do whatever you are doing with existing Classs parameter
  }

  public void run() {
    driver.setMyVariable("test");
  }

And also make changes to Driver class

public class Driver extends Application{

  //create socket handlers
  Runnable myNewThread = new workerThread(this, this.getClass());

 //variables
 private String lastMessage = "";

 //getters and setters
 public String setMyVariable() {
   this.MyVariable = MyVariable;
 }

 //main
 public static void main(String[] args) {
   //launch threads
   new Thread(new Driver().myNewThread).start();
 }
}

UPDATE:

And because myNewThread variable is also non-static you have to do the following in Driver.main() to be able to compile:

new Thread(new Driver().myNewThread).start();
like image 106
Ivan Avatar answered Oct 21 '25 01:10

Ivan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!