简体   繁体   English

值未插入到Hashmap中

[英]Values are not getting inserted into Hashmap

public class FileReaderServer implements Runnable
{
    private Map<String, String> mapp = new HashMap<String, String>();

    public void searchWords()
    {
        try
        {
            BufferedReader br = new BufferedReader(new FileReader(input));
            while ( (line = br.readLine()) != null )
            {
                boolean success = tree.search(line);
                if ( success )
                    mapp.put(line, "TRUE");
                else
                    mapp.put(line, "FALSE");
            }
        }
        catch( Exception ex )
        {
            System.out.println( ex );
        }
    }

    public void run()
    {
        searchWords();
    }

    public void printMap()
    {
        Iterator it = mapp.entrySet().iterator();
        while ( it.hasNext() ) 
        {
            Map.Entry pair = (Map.Entry)it.next();
            System.out.println(pair.getKey() + " = " + pair.getValue());
        }
    }

    public static void main( String[] args )
    {
        try
        {
            FileReaderServer server = new FileReaderServer("keywords.txt");
            server.createTree();

            Thread t1 = new Thread(new FileReaderServer());
            Thread t2 = new Thread(new FileReaderServer());
            Thread t3 = new Thread(new FileReaderServer());             

            t1.start();
            t2.start();
            t3.start();

            t1.join();
            t2.join();
            t3.join();

            server.printMap();
        }
        catch( Exception ex )
        {
            System.out.println(ex);
        }
    }

This is cut-down version of my original class enough to figure out issue I believe. 这是我原始课程的简化版本,足以找出我认为的问题。 ( if not please let me know to paste some more code.) (如果没有,请让我知道粘贴更多代码。)

Issue is that in "printMap" nothing is getting printed. 问题是在“ printMap”中什么也没打印。 However, code has reached 但是,代码已达到

boolean success = tree.search(line);
if ( success )
{
    System.out.println(line + "TRUE");   // This is getting printed.
    mapp.put(line, "TRUE");
}
else
    mapp.put(line, "FALSE");

EDIT :- One more question here. 编辑:-这里还有一个问题。 I'm trying to make searchWords synchronized . 我正在尝试使searchWords synchronized However, I am passing different instances to each of the created thread.So, is synchronization a property of object OR a class. 但是,我将不同的实例传递给每个创建的线程。因此,同步是对象的属性还是类。 ie whether any of these threads could be executing that function concurrently. 也就是说,这些线程中的任何一个是否可以同时执行该功能。

You pass another instance of FileReaderServer to each thread: 您将FileReaderServer的另一个实例传递给每个线程:

        Thread t1 = new Thread(new FileReaderServer());
        Thread t2 = new Thread(new FileReaderServer());
        Thread t3 = new Thread(new FileReaderServer());   

But you try to get values from: 但是您尝试从以下方法获取值:

        FileReaderServer server = new FileReaderServer("keywords.txt");

...

        server.printMap();

If you will pass server instance to each of these three threads - you will get unexpected behaviour due unsynchronized nature of java.util.HashMap . 如果将服务器实例传递给这三个线程中的每个线程,则将由于java.util.HashMap的不同步特性而导致意外行为。 Replace it with java.util.concurrent.ConcurrentHashMap . 将其替换为java.util.concurrent.ConcurrentHashMap

UPD1 If you will mark searchWords() as synchronized - you will loose all benefits of concurrency, because all your 3 threads will execute searchWords() sequentially. UPD1如果您将searchWords()标记为已同步 -您将失去并发的所有好处,因为您的所有3个线程都将顺序执行searchWords()

So I'm still insist on using ConcurrentHashMap : 所以我仍然坚持使用ConcurrentHashMap

private Map<String, String> mapp = new ConcurrentHashMap<String, String>();

Or you may simply wrap HashMap instance with Collections.synchronizedMap(...) like this: 或者,您可以像这样简单地用Collections.synchronizedMap(...)包装HashMap实例:

private Map<String, String> mapp = Collections.synchronizedMap(new HashMap<String, String>())

Your problem is, that you try to get your lines from server . 您的问题是,您尝试从server获得线路。 But the server object will not get started. 但是服务器对象将无法启动。 You have to start your threads like so: 您必须像这样启动线程:

Thread t1 = new Thread(server);
Thread t2 = new Thread(server);
Thread t3 = new Thread(server);   

In this case you have to think about good synchronization. 在这种情况下,您必须考虑良好的同步。

You are printing the HashMap member of the FileReaderServer instance referred by the server variable, but that's not the HashMap you are adding entries to. 您正在打印server变量引用的FileReaderServer实例的HashMap成员,但这不是要向其中添加条目的HashMap

You are adding the entries to the HashMap s of the FileReaderServer instances passed to the Thread s you are creating. 您正在将条目添加到传递给您正在创建的ThreadFileReaderServer实例的HashMap中。

You may want to make mapp static if you want it to be shared by all instances of FileReaderServer . 如果希望由FileReaderServer的所有实例共享mapp则可能需要使其mapp静态。 However, if you do that, you may encounter synchronization issues, so perhaps you should use a ConcurrentHashMap . 但是,如果这样做,则可能会遇到同步问题,因此也许应该使用ConcurrentHashMap

Where is the Constructor that takes a String File-name. 带字符串文件名的构造方法在哪里。 Create a constructor that takes a String file-name as parameter. 创建一个将String文件名作为参数的构造函数。

FileReaderServer server = new FileReaderServer("keywords.txt");

Where are you initializing the variable input in: 您在哪里初始化变量输入:

BufferedReader br = new BufferedReader(new FileReader(input));

When it creates a thread FileReaderServer does not know which file to read. 创建线程时,FileReaderServer不知道要读取哪个文件。

Thread t1 = new Thread(new FileReaderServer());

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

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