|
1 | 1 | package org.tj.study.thread.readfile; |
2 | 2 |
|
| 3 | +import java.io.*; |
| 4 | + |
3 | 5 | /** |
4 | 6 | * Created by 001 on 16/8/22. |
5 | 7 | */ |
6 | | -public class ReadFile { |
| 8 | +public class ReadFile implements Runnable{ |
| 9 | + |
| 10 | + int sum = 0; |
| 11 | + BufferedReader bufferedReader; |
| 12 | + String str; |
7 | 13 |
|
8 | | - public static void main(String[] args) { |
9 | | - FileR |
| 14 | + public ReadFile(String filename){ |
| 15 | + try { |
| 16 | + bufferedReader = new BufferedReader(new FileReader(new File(filename))); |
| 17 | + } catch (FileNotFoundException e) { |
| 18 | + e.printStackTrace(); |
| 19 | + } |
10 | 20 | } |
11 | 21 |
|
| 22 | + static void readfile(String fileName) throws IOException { |
| 23 | + BufferedReader bufferedReader1 = new BufferedReader(new FileReader(new File(fileName))); |
| 24 | + int sum = 0; |
| 25 | + String str; |
| 26 | + while ((str = bufferedReader1.readLine())!=null){ |
| 27 | + sum += Integer.valueOf(str); |
| 28 | + } |
| 29 | + |
| 30 | + } |
| 31 | + |
| 32 | + public static void main(String[] args) throws IOException { |
| 33 | + |
| 34 | + for (int i=0;i<8;i++){ |
| 35 | + long start = System.currentTimeMillis(); |
| 36 | + readfile("thread1.txt"); |
| 37 | + readfile("thread2.txt"); |
| 38 | + System.out.println("单线程耗时: "+(System.currentTimeMillis() - start)); |
| 39 | + |
| 40 | + start = System.currentTimeMillis(); |
| 41 | + ReadFile readFile1 = new ReadFile("thread1.txt"); |
| 42 | + ReadFile readFile2 = new ReadFile("thread2.txt"); |
| 43 | + Thread thread1 = new Thread(readFile1); |
| 44 | + Thread thread2 = new Thread(readFile2); |
| 45 | + thread1.start(); |
| 46 | + thread2.start(); |
| 47 | + try { |
| 48 | + thread1.join(); |
| 49 | + thread2.join(); |
| 50 | + } catch (InterruptedException e) { |
| 51 | + e.printStackTrace(); |
| 52 | + } |
| 53 | + System.out.println("多线程耗时: "+(System.currentTimeMillis() - start)); |
| 54 | +// System.gc(); |
| 55 | + } |
| 56 | + |
| 57 | + |
| 58 | + } |
| 59 | + |
| 60 | + |
| 61 | + @Override |
| 62 | + public void run() { |
| 63 | + try { |
| 64 | + while ((str = bufferedReader.readLine())!=null){ |
| 65 | + sum += Integer.valueOf(str); |
| 66 | + } |
| 67 | + } catch (IOException e) { |
| 68 | + e.printStackTrace(); |
| 69 | + } |
| 70 | + } |
12 | 71 | } |
0 commit comments