同步关键字是否阻止线程在锁定时使用其自己的变量? [英] Does synchronize keyword prevent a thread from using its own variable while locked?

查看:61
本文介绍了同步关键字是否阻止线程在锁定时使用其自己的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们举个例子:

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

让我们假设在给定时间有3个用户(用户0,用户1,用户2)连接到服务器.
用户1为用户0的对象获取了内部锁.可以确定的是,用户2在用户1仍拥有该对象时仍无法获得用户0的锁.用户1持​​有锁定时,用户0自己可以使用method2()更改c的值吗?如果是这样,是否有一种方法可以使variable c在拥有它的线程和其他线程之间进行同步?

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?

推荐答案

您可以将C设为类DBServer的静态变量,这样所有线程都可以访问它.

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

现在,这将需要您更改method2()才能进行同步.

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

,如果您要这样做,则要在这些新条款下回答您的问题,用户0将无法在用户1的控制下更改变量C.

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.

这篇关于同步关键字是否阻止线程在锁定时使用其自己的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆