我可以将它组合成一个循环吗?

时间:2015-02-22 18:17:31

标签: java multithreading

嗨我有一个在Thread内部运行的方法,该方法使用fileOutputStream流或RandomaccessFile进行写入。我有它在2循环我喜欢将它组合成1但我失去了如何。这是run方法。

   package treadmakestop;

import java.awt.EventQueue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;

/**
 *
 * @author brett
 */
public class Worker implements Runnable {

    private final ReentrantLock PAUSELOCK;
    private final Condition PAUSECONDITION;
    private final AtomicBoolean PAUSED;
    private final AtomicBoolean KEEPRUNNING;
    private final AtomicBoolean KILLSTREAM;
    private final File FILEIN = new File("C:\\Users\\brett\\Documents\\Back to the Beginning Origins Nova Neil Degrasse Tyson   Documentary-D-EXw5CdPtM.mp4");
    private final File WORKINGDIR = new File(System.getProperty("user.home") + File.separator + "Documents" + File.separator + "ConvertedTvFiles" + File.separator);
    private final File FILEOUT = new File(WORKINGDIR + File.separator + "spew" + ".mp4");
    private final JProgressBar TVPG;
    private final long LENGTH = FILEIN.length();
    private final byte[] b = new byte[1024];
    private FileOutputStream FOUTS;
    private FileInputStream FINS;
    private RandomAccessFile RandFileOut;
    private RandomAccessFile RandFileIn;
    private int r;
    private long Counter = 1;

    public Worker(JProgressBar tvpg) {
        PAUSED = new AtomicBoolean();
        KEEPRUNNING = new AtomicBoolean(true);
        KILLSTREAM = new AtomicBoolean(false);
        PAUSELOCK = new ReentrantLock();
        PAUSECONDITION = PAUSELOCK.newCondition();
        TVPG = tvpg;
    }

    /**
     * This is the main thread and copy file operation
     */
    @Override
    public void run() {
        System.out.println("Runnable has started");
        int progress;
        try {
            createFirstFileStream();
            while ((r = FINS.read(b)) != -1 && KEEPRUNNING.get()) {
                checkPauseState();
                if (!KILLSTREAM.get()) {
                    Counter += r;
                    FOUTS.write(b, 0, r);
                    progress = (int) Math.round(100 * Counter / LENGTH);
                    updateProgress(Math.min(progress, 100));
                } else {
                    killFileStream();
                    break;
                }
            }
            createRandomFile();
            while ((r = RandFileIn.read(b)) != -1 && KEEPRUNNING.get()) {
                checkPauseState();
                if (KILLSTREAM.get()) {
                    Counter += r;
                    RandFileOut.write(b, 0, r);
                    progress = (int) Math.round(100 * Counter / LENGTH);
                    updateProgress(Math.min(progress, 100));
                } else {
                    killRandFile();
                    break;
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Runnable has exited");
    }

    public void createFirstFileStream() throws IOException {
        FINS = new FileInputStream(FILEIN);
        FOUTS = new FileOutputStream(FILEOUT);
    }

    public void createRandomFile() throws IOException {
        RandFileIn = new RandomAccessFile(FILEIN, "rw");
        RandFileIn.seek(FILEOUT.length());
        long pointer = RandFileIn.getFilePointer();
        RandFileOut = new RandomAccessFile(FILEOUT, "rw");
        RandFileOut.seek(pointer);
    }

    public boolean isPaused() {
        return PAUSED.get();
    }

    public void pause() {
        KILLSTREAM.set(true);
        PAUSED.set(true);
    }

    public void resume() {
        PAUSED.set(false);
        PAUSELOCK.lock();
        try {
            PAUSECONDITION.signal();
        } finally {
            PAUSELOCK.unlock();
        }
    }

    protected void checkPauseState() {
        while (PAUSED.get()) {
            PAUSELOCK.lock();
            try {
                PAUSECONDITION.await();
            } catch (Exception e) {
            } finally {
                PAUSELOCK.unlock();
            }
        }
    }

    protected void updateProgress(int progress) {
        if (EventQueue.isDispatchThread()) {
            TVPG.setValue(progress);
            if (KEEPRUNNING.get() == false) {
                TVPG.setValue(0);
            }
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    updateProgress(progress);
                }
            });
        }
    }

    public void killFileStream() throws IOException {
        FINS.close();
        FOUTS.flush();
        FOUTS.close();
    }

    public void killRandFile() throws IOException {
        RandFileIn.close();
        RandFileOut.close();
    }

    public synchronized void stop() {
        KEEPRUNNING.set(false);
        resume();
    }

}

这是整个班级

1 个答案:

答案 0 :(得分:-1)

这样的事情应该有效:

createFirstFileStream();
createRandomFile();
InputStream combined = new SequentialInputStream(FINS, 
        Channels.createInputStream(RandomFileIn.getChannel());
// your while loop
while ((r = combined.read(b)) != -1 && KEEPRUNNING.get()) {

    if (!KILLSTREAM.get()) {
        Counter += r;
        FOUTS.write(b, 0, r);
        progress = (int) Math.round(100 * Counter / LENGTH);
        updateProgress(Math.min(progress, 100));
    } else {
        killFileStream();
        break;
    }
}

或者,将循环包装在函数中并调用它两次,使用上面的Channels调用将RandomAccessFile包装到InputStream。