Does synchronize keyword prevent a thread from using its own variable while locked?

喜夏-厌秋 提交于 2020-01-25 04:24:06

问题


Lets take an example:

public class DBServer {
static boolean listening = false;
private static ServerSocket serverSocket = null;
private static Socket clientSocket = null;
static List<ClientThread> users = null;

public static void main(String[] args) {
    users= new LinkedList();
    int portNumber = 0;//some valid port number
    System.out.println("Now using port number=" + portNumber);
    try {
        serverSocket = new ServerSocket(portNumber);
    } catch (IOException e) {
        System.out.println(e);
    }

    while (listening) {
        try {
            System.out.println("Number of users connected: " + users.size());
            clientSocket = serverSocket.accept();
            System.out.println("Someone just joined.");
            ClientThread ct= new ClientThread(clientSocket);
            users.add(ct);
            ct.start();
        }catch (IOException e) {
            System.out.println(e);
        }
    }
}
}//End of class

public class ClientThread extends Thread {
    int c = 0;
    //some other variables
    ClientThread(Socket s){
        this.clientSocket= s; 
    }
    void doSomething(){
        ClientThread ct = DBServer.users.get(0);
        synchronized(ct){
            ct.c++;//or some other operation on c
        }
    }
    void method2(){
        c++;//or some other operation on c
    }

    //some other methods

    public void run(){
    //some never ending logic that decides which method is being called
    }
}//End of class

Let's assume that there are 3 users(User 0, User 1, User 2) connected to the server at a given time.
User 1 obtains the intrinsic lock for the object of User 0. It is certain that User 2 can't obtain the lock for User 0 while User 1 still posses it. Can User 0 himself change the value of c using method2() while the lock is held by User 1? If so, is there a way to make variable c synchronized between the thread owning it and other threads?


回答1:


So for your following question //If so, is there a way to make variable c synchronized?

Go for AtomicInteger which will prevent the race condition,

AtomicInteger c;




回答2:


you can make C a static variable of class DBServer that way all threads will have access to it.

now, that will require you to change method2() to be synchronized.

and if you do that, to answer your question under these new terms, user 0 will not be able to change variable C while its under the control of user 1.



来源:https://stackoverflow.com/questions/35217897/does-synchronize-keyword-prevent-a-thread-from-using-its-own-variable-while-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!