Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我可以把它合并成一个循环吗?_Java_Multithreading - Fatal编程技术网

Java 我可以把它合并成一个循环吗?

Java 我可以把它合并成一个循环吗?,java,multithreading,Java,Multithreading,嗨,我有一个run方法,它在一个线程中,使用fileOutputStream流或RandomaccessFile进行写入。我把它分成2个while循环,我想把它合并成1个while循环,但我不知道如何组合。下面是run方法 package treadmakestop; import java.awt.EventQueue; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStrea

嗨,我有一个run方法,它在一个线程中,使用fileOutputStream流或RandomaccessFile进行写入。我把它分成2个while循环,我想把它合并成1个while循环,但我不知道如何组合。下面是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();
    }

}

下面是整个课程

类似的内容应该可以:

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

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

?或者你可以把循环放在一个单独的函数中。@AdrianLeonhard我不知道它是如何应用的。我正在使用RandomAccessFile,这样我就可以从它停止的地方恢复线程??FINS和RandFileIn的类型是什么?它们是物体吗?如果是这样的话,按照惯例,它们不应该大写。对不起,阿德里安,我还是有点迷路了?我不知道如何使用它?我能再问一点建议吗?不,那似乎不起作用