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

4

This question already has an answer here:

Threads and file writing 6 answers

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

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

Спасибо.

Error: User Rate Limit Exceededstackoverflow.com/questions/9972549/threads-and-file-writing Alex Stybaev
Error: User Rate Limit Exceeded johnnycrash
Error: User Rate Limit Exceeded live-love
Error: User Rate Limit Exceeded Martin James
Error: User Rate Limit Exceeded Martin James

Ваш Ответ

3   ответа
1

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
}
21

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!!");
Error: User Rate Limit Exceededstatic methods can be synchronized tooError: 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 Exceededsynchronized
6

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);
  }
}
Error: User Rate Limit ExceededFile-lock objects are safe for use by multiple concurrent threads.Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded

Похожие вопросы