1. 程式人生 > >Java 非同步同時寫多個檔案,寫完之後通知子執行緒

Java 非同步同時寫多個檔案,寫完之後通知子執行緒

思路:

        是主執行緒和多個寫檔案執行緒之間同步,每寫完一個檔案計數加1,如果計數值等於當前寫檔案個數的時候,表示檔案已經全部寫完。此時通過條件變數通知在該條件變數等待的主執行緒。此時主執行緒被喚醒,可以在所有檔案被寫完的條件下做一些動作

程式碼:

package com.example.task.thread;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AsyncFileSave {

    private Lock lock = new ReentrantLock();

    private Condition saveFinishedCond = lock.newCondition();

    private int totalSaveThread;

    private int finishCount = 0;

    private class SaveFileAction implements Runnable {
        private String filePath;

        public SaveFileAction(String filePath) {
            this.filePath = filePath;
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub
            OutputStream os = null;
            try {
                os = new FileOutputStream(filePath);
                Thread.sleep(2000);
                os.write(filePath.getBytes());

                lock.lock();
                finishCount++;
                if (finishCount == totalSaveThread) {
                    saveFinishedCond.signal();
                }

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {

                lock.unlock();

                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }

    }

    public void BatchSave(int num) {
        totalSaveThread = num;
        for (int i = 0; i < totalSaveThread; i++) {
            new Thread(new SaveFileAction("test" + i)).start();
        }

        try {
            lock.lock();
            saveFinishedCond.await();
            System.out.println("save finished");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {

        AsyncFileSave instance = new AsyncFileSave();

        instance.BatchSave(5);

    }

}