简体   繁体   中英

multiple threads - exclusive access to class member variable?

I have a class which stores several strings and integers. These values are being continually updated by my program.

In the same program I also have a simple socket server which deals with incoming requests for the data contained in the object of my class. Because the server code contains a while(true) loop, I'm assuming I need to place the code in a separate thread. Otherwise nothing else will get executed once I enter this loop? I will then pass a reference to my class to the server thread so the values can be obtained.

static ServerSocket socket1;
static Socket connection;

while (true) {
    connection = socket1.accept();
    ...
 }

Anyway, I'm wondering that if I were to create a separate server thread, then I might run into synchronization issues. When a certain condition is met in my program, the members of the class are updated. I would not like the server to be able to read the values if they are currently in the process of being updated. How can I go about doing this?

You can implement the runnable interface and write your loop in the run() method.

public class SocketClass implements Runnable {
  // variables

  // running the thread
  public void run() {
    while(true) {
      // loop
    }
  }
}

In the main thread you can then start a new thread with new Thread(...).start() .

SocketClass socket = new socketClass();
new Thread(socket).start();

You then have a reference to your SocketClass where you can access the variables. You should synchronize on the class or on the object you are working when reading or updating data.

// in main thread
synchronized(socket) {
  // read data
}

// in SocketClass
synchronized(this) {
  // write data
}

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