简体   繁体   中英

Thread Synchronization - Printing to a FIle

I have two threads in my program, a "Sender" and "Receiver" thread. In both threads at various times, I need to write to a file. However, I am finding that sometimes they are both writing to the file at the same time causing the input to become jumbled.

Is there a way for the program to only have one thread write to the file at a given time?

In another thread: Thread Synchronization , I was told to use a Synchronization block. However, when I try implement this I get errors as to how I am defining:

private final Object lock = new Object();

It initially says:

Cannot make a static reference to the non-static field lock

If I change it to static, it then says

The method sychronized(Object) is undefined for the type SendThread .

Does synchronized(lock) NEED to be inside a function or can it just be around some code?

If this method would help my current issue, where and how should I define the above?

The structure of my code is as follows:

public class my_main_class{

    private final static Object lock = new Object();

    public static void main (String[] args) throws Exception{

        class SendThread implements Runnable {

            synchronized (lock){
                  // contains code to print to text file
            }
         }

         class ReceiveThread implements Runnable {

            synchronized (lock){
                 // contains code to print to text file
            }
         }

}

synchronized marks a block of code as being executable only while holding a specific lock. And in Java, you can't insert code anywhere, it has to be inside a method or an initialisation block.

So your problem is not a multi-threading one but a basic Java syntax issue.

I suppose this could do what you expected:

class SendThread implements Runnable {
    public void run() {
        synchronized (lock){
              // contains code to print to text file
        }
    }
 }

 class ReceiveThread implements Runnable {
    public void run() {
        synchronized (lock){
              // contains code to print to text file
        }
    }
 }

Then in your main:

private final static Object lock = new Object();

public static void main (String[] args) throws Exception{
    Runnable send = new SendThread();
    Runnable recv = new ReceiveThread();
    new Thread(send).start();
    new Thread(recv).start();
}

I have no idea what those methods are supposed to do so it might not be the right design, but at least it compiles and the two run methods are mutually exclusive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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