Javaマルチスレッド生成テストファイル

2981 ワード

import java.io.File;
import java.io.FileInputStream;


import java.io.FileOutputStream;

import org.boris.expr.Expr;
import org.boris.expr.ExprEvaluatable;
import org.boris.expr.parser.ExprParser;
import org.boris.expr.util.Exprs;
import org.boris.expr.util.SimpleEvaluationContext;
// expr
//http://nchc.dl.sourceforge.net/project/expr4j/expr4j/0.0.1/expr4j-0.0.1.zip
// 
public class TestData {

	public static void main(String[] args) {

		if (args.length != 3) {
			System.out.println("Usage: inputFile size(M)/Expr threads");
			//java -jar testData.jar data5g\ .TXT 1024*5 15
			return;
		}
		File inputFile = new File(args[0]);
		if(!inputFile.exists())
		{
			System.out.println(" ");
		
			return;		
		}	
		Expr expr = null;
		try {
			 expr = ExprParser.parse(args[1]);
			Exprs.toUpperCase(expr);		
			if (expr instanceof ExprEvaluatable) {
				expr = ((ExprEvaluatable) expr).evaluate(new SimpleEvaluationContext());
			}
			System.out.println(" :"+expr);
		} catch (Exception e) {
			e.printStackTrace();
			return ;
		}
				
		long size = (long) (1024  * Double.parseDouble(expr.toString()));// m
		long fileSize = inputFile.length() / 1024;
		int threads = Integer.parseInt(args[2]);

		long filecount = size / fileSize;
		long parts = filecount / threads;//  
		Thread[] mythreads=new MyThread[threads];
		for (int i = 0; i < threads; i++) {
			mythreads[i] = new MyThread(i+1, i * parts, (i + 1) * parts,inputFile);
			mythreads[i].start();
		}
		while(true)
		{
			boolean isAllFinish=true;
			for (Thread thread : mythreads) {
				if(thread.isAlive())
				{
					isAllFinish=false;
				}
			}
			if(isAllFinish)
			{
				System.out.println(" ");
				break;
			}
		}

	}

	static class MyThread extends Thread {

		private int id;
		private long startIndex;
		private long endIndex;
		private File inputFile;
		//private boolean isFinish=false;

		public MyThread(){}
		
		public MyThread(int i, long l, long m, File inputFile) {
			this.id = i;
			this.startIndex = l;
			this.endIndex = m;
			this.inputFile = inputFile;
		}

		@Override
		public void run() {

			try {
				System.out.println(" "+id+" ");
				for (long i = startIndex; i < endIndex; i++) {
					copyFile(inputFile, new File(inputFile.getParent(), (i+1)+ inputFile.getName()));
				}
				//isFinish=true;
				System.out.println(" "+id+" ");
			} catch (Exception e) {
				e.printStackTrace();
			}
			super.run();
		}

	}

	private static void copyFile(File inputfile, File outputFile)
			throws Exception {

		FileInputStream fileInputStream = new FileInputStream(inputfile);
		FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = fileInputStream.read(buffer)) != -1) {
			fileOutputStream.write(buffer, 0, len);
		}
		fileOutputStream.flush();
		fileOutputStream.close();
		fileInputStream.close();

	}
}