4

Вопрос по multithreading, java – Написать в текстовый файл из нескольких потоков? [Дубликат]

This question already has an answer here:

у меня есть 20 потоков, которые пишут с помощью функции println () в файл с именем results.txt. Как я могу синхронизировать их все?

Я отмечаю, что каждый раз, когда моя программа запускается, у меня есть различное количество строк текста в results.txt.

Спасибо.

  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceededsynchronized

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit ExceededenumError: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit ExceededclassError: User Rate Limit ExceededobjectError: User Rate Limit ExceededsynchronizedError: User Rate Limit Exceeded

    от
  • Error: User Rate Limit ExceededFile-lock objects are safe for use by multiple concurrent threads.Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceededstatic methods can be synchronized tooError: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от Martin James
  • Error: User Rate Limit Exceededstackoverflow.com/questions/9972549/threads-and-file-writing

    от Alex Stybaev
  • Error: User Rate Limit Exceeded

    от Martin James
  • Error: User Rate Limit Exceeded

    от live-love
  • Error: User Rate Limit Exceeded

    от johnnycrash
  • 21

    Error: User Rate Limit Exceeded

    package com.test.singleton;
    
    public class Singleton {
        private static final Singleton inst= new Singleton();
    
        private Singleton() {
            super();
        }
    
        public synchronized void writeToFile(String str) {
            // Do whatever
        }
    
        public Singleton getInstance() {
            return inst;
        }
    
    }
    

    Singleton.getInstance().writeToFile("Hello!!");
    

  • 1

    Error: User Rate Limit Exceeded

    RandomAccessFile

    try {
        final RandomAccessFile file = new RandomAccessFile("/path/to/your/result.txt", "rw");
        final int numberOfThread = 20;
        final int bufferSize = 512;
        ExecutorService pool = Executors.newFixedThreadPool(numberOfThread);
        final AtomicInteger byteCounter = new AtomicInteger(0);
        final byte[] yourText = "Your data".getBytes();
        for (int i = 0; i < yourText.length; i++) {
            pool.submit(new Runnable() {
                @Override
                public void ,run() {
                    int start = byteCounter.getAndAdd(bufferSize);
                    int chunkSize = bufferSize;
                    if (start + bufferSize > yourText.length) {
                        chunkSize = yourText.length - start;
                    }
                    byte[] chunkData = new byte[chunkSize];
                    System.arraycopy(yourText, start, chunkData, 0, chunkSize);
                    try {
                        file.write(chunkData);
                    } catch (IOException e) {
                        //exception handle
                    }
                }
            });
        }
        file.close();
    } catch (Exception e) {
        //clean up
    }
    

  • 6

    Error: User Rate Limit Exceeded

    FileOutputStream

    FileOutputStream file = ...
    ....
    // Thread safe version.
    void write(byte[] bytes) {
      try {
        boolean written = false;
        do {
          try {
            // Lock it!
            FileLock lock = file.getChannel().lock();
            try {
              // Write the bytes.
              file.write(bytes);
              written = true;
            } finally {
              // Release the lock.
              lock.release();
            }
          } catch ( OverlappingFileLockException ofle ) {
            try {
              // Wait a bit
              Thread.sleep(0);
            } catch (InterruptedException ex) {
              throw new InterruptedIOException ("Interrupted waiting for a file lock.");
            }
          }
        } while (!written);
      } catch (IOException ex) {
        log.warn("Failed to lock " + fileName, ex);
      }
    }