多執行緒 -- 移動檔案(生產者,消費者模式應用)

TheSnowBoy_2發表於2016-07-03

期待實現的效果:

  • Thread producer 負責向 某資料夾 (GEXF_DIR)中寫檔案。(從ORIGIN_DIR 移動到 GEXF_DIR)
  • Thread consumer 負責從GEXF_DIR中取出資料到GEXF_SAVED_DIR中。


整體示意圖如下:


Thread producer中的流程:


Thread consumer 流程圖如下:



程式碼如下:

package tree.test.testThread;

import java.io.File;

import tree.utils.FileUtils;

public class TestFileMove {

	public final static String ORIGIN_DIR = "test/dirTest/";
	public final static String GEXF_DIR = "test/dirTest/gexf_files/";
	public final static String GEXF_SAVED_DIR = "test/dirTest/gexf_saved/";
	private static File gexfFiles;
	private static boolean isFinished = false;

	public static void main(String[] args) {
		File gexfDir = new File(GEXF_DIR);
		Consumer consumer = new Consumer();
		consumer.setGexfFiles(gexfDir);

		Producer producer = new Producer();
		producer.setGexfFiles(gexfDir);

		isFinished = false;
		new Thread(producer).start();
		new Thread(consumer).start();
		System.out.println("main ended `````");

	}

	static class Consumer implements Runnable {
		private File dir;

		public void run() {

			while (!isFinished) {
				synchronized (dir) {
					// TODO
					File files[] = dir.listFiles();
					for (int i = 0; i < files.length; i++) {
						if (FileUtils.isRequiredExtention(files[i].getName(), ".gexf")) {
							FileUtils.moveFileToAnother(files[i], GEXF_SAVED_DIR);
						}
					}
				}
				try {
					Thread.sleep(500);
					Thread.yield();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println("consumer ended `````");
		}

		public void setGexfFiles(File gexfDir) {
			dir = gexfDir;
		}

	}

	static class Producer implements Runnable {
		private File dir;

		public void run() {

			// TODO
			File originDir = new File(ORIGIN_DIR);
			File files[] = originDir.listFiles();
			for (int i = 0; i < files.length; i++) {
				synchronized (dir) {
					if (FileUtils.isRequiredExtention(files[i].getName(), ".gexf")) {
						FileUtils.moveFileToAnother(files[i], GEXF_DIR);
					}
				}
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			isFinished = true;
			System.out.println("producer ended `````");
		}

		public void setGexfFiles(File gexfDir) {
			dir = gexfDir;
		}

	}

}


相關文章