简体   繁体   English

哪些变量是java中多线程的accessbile?

[英]Which variables are accessbile for multiple threads in java?

I am working on a simple message queue where I am creating separate thread for new connection. 我正在一个简单的消息队列,我正在为新连接创建单独的线程。 I want to know which variables are accessible and can be modified by multiple threads. 我想知道哪些变量是可访问的,并且可以由多个线程修改。

class RequestHandler implements Runnable {

    Socket socket;

    protected RequestHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() { ..........

In above code is socket can be accessed by multiple threads, if yes then how do I protect it. 在上面的代码中,socket可以被多个线程访问,如果是,那么我该如何保护它。

Complete code is available at. 完整的代码可在。 https://github.com/nakshay/JQueue https://github.com/nakshay/JQueue

I am new to multithreading, please modify question if requried. 我是多线程的新手,如果需要,请修改问题。

If the socket variable can be accessed by multiple threads you need synchronize access to the variable. 如果多个线程可以访问套接字变量,则需要同步对变量的访问。

One of the ways is to create a wrapper, which basically will synchronize methods calls[1]. 其中一种方法是创建一个包装器,它基本上会同步方法调用[1]。

And then wrap your socket in the constructor: 然后在构造函数中包装您的套接字:

class RequestHandler implements Runnable {

    Socket socket;

    protected RequestHandler(Socket socket) {
        this.socket = new SynchronizedSocket(socket);
    }

    public void run() { ..........

[1] - https://gist.github.com/Sammers21/a6635213276e9ea064a5a4f20dd53c11 [1] - https://gist.github.com/Sammers21/a6635213276e9ea064a5a4f20dd53c11

Not shown in the post: You actually create a new RequestHandler and Socket for every thread, so since the socket is not static, you are fine. 帖子中没有显示:你实际上为每个线程创建了一个新的RequestHandler和Socket,所以由于套接字不是静态的,你很好。 Each thread handles its own connection (represented by the Socket). 每个线程处理自己的连接(由Socket表示)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM