java - 无法借助 Java 中的同步方法获得答案

标签 java multithreading synchronized

我必须使用 Java 中的多线程从文件 F1 和 F2 中读取内容并将其移动到新文件 (f3)。我面临的问题是,当我在方法中使用同步时,我无法得到答案,但是当我不同步方法时,我能够得到答案。

下面是同步方法的代码,只打印一个文件的内容:

package com.company;
import java.io.*;
import java.io.FileReader;

public class FileMerge{
    public static void main(String[] args) throws IOException, InterruptedException {
        WriteToFile pc = new WriteToFile();
        //Create a Thread1 to read the content of file 1
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                   try {
                    pc.file1();
                } catch (InterruptedException | IOException e) {
                    System.out.println(e);

                }
            }
        });

        // Create  Thread 2 to read the content of file 2
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    pc.file2();
                } catch (InterruptedException | IOException e) {
                    System.out.println(e);

                }
            }
        });


        //Start the Thread
        t1.start();
        t2.start();

        t1.join();
        t2.join();
    }

    public static class WriteToFile{
        PrintWriter pw = new PrintWriter("C:/Users/paras.jain/Desktop/des.txt");

        public WriteToFile() throws FileNotFoundException {
        }


        public synchronized void file1() throws InterruptedException, IOException {
            // BufferedReader object for file1.txt
            BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\paras.jain\\Desktop\\f.txt"));
            String line = br.readLine();
            //System.out.println("----------" + line);

            // loop to copy each line of
            // file1.txt to file3.txt
            while (line != null) {
                pw.println(line);

                line = br.readLine();
            }
            br.close();
            pw.close();

        }

        public  synchronized void file2() throws InterruptedException, IOException {

            BufferedReader br1 = new BufferedReader(new FileReader("C:/Users/paras.jain/Desktop/f2.txt"));
            String line2 = br1.readLine();
            //System.out.println("----------" + line2);


            // loop to copy each line of
            // file2.txt to file3.txt
            while (line2 != null) {
                pw.println(line2);
                line2 = br1.readLine();
                //System.out.println("----------" + line2);
            }
            br1.close();
            pw.close();

        }
    }
}

以上代码的输出是:

File 1 line 1 
File 1 line 2
File 1 line 3

当我运行代码WITHOUT synchronize 方法时,我得到以下输出:

File 1 line 1
File 1 line 2
File 2 line 1
File 2 line 2
File 1 line 3
File 2 line 3

为什么输出会有所不同?以及如何借助 Synchronized 方法获得第二个输出?

最佳答案

file1()file2()方法是同步的,其中一个必须在另一个运行之前完成。

由于您启动了运行 file1() 的线程首先,它可能会赢得比赛,所以 file1()必须在 file2() 之前完成可以运行。

不幸的是,file1() 关闭 PrintWriter,所以当 file2()运行,所有 pw.println(...)调用默默地失败

为什么沉默?因为那是他们定义它的方式。参见 PrintWriter 的 javadoc :

Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().

关于java - 无法借助 Java 中的同步方法获得答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58526115/

相关文章:

java - 在 Java 中使用泛型参数(必须扩展泛型类)扩展抽象方法

.class 的 Java 同步块(synchronized block)

java - 一般 synchronizedList 问题

java.sql.SQL警告: [Microsoft][SQLServer 2000 Driver for JDBC]Database changed to X

javascript - 无法打开与同一 SockJS 端点的多个连接

java - 流到字符串 : merging multiple files into a single string

c# - 有没有办法可靠地检测 CPU 内核总数?

python - 如何在仍然显示摄像机记录的同时根据训练有素的模型检查图像?

java - 如何从另一个 Activity 访问在一个 Activity 中实例化并在其自己的线程中运行的对象?

java - 同步新的读取和内存屏障