-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMultiThreaded.java
More file actions
84 lines (73 loc) · 2.54 KB
/
MultiThreaded.java
File metadata and controls
84 lines (73 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.*;
import java.nio.*;
import java.io.*;
import java.util.concurrent.*;
class CopyFileScheduler {
private final Collection<Runnable> tasks = new ArrayList<Runnable>();
public void addTask(final Runnable task) {
tasks.add(task);
}
public void executeTasks() throws InterruptedException {
final ExecutorService threads = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
try {
final CountDownLatch latch = new CountDownLatch(tasks.size());
for (final Runnable task : tasks)
threads.execute(new Runnable() {
public void run() {
try {
task.run();
} finally {
latch.countDown();
}
}
});
latch.await();
} finally {
threads.shutdown();
}
}
}
class MultiThreadedCopyFileTask implements Runnable{
private String srcFilePath;
private String destFilePath;
public MultiThreadedCopyFileTask(String srcFilePath, String destFilePath){
this.srcFilePath = srcFilePath;
this.destFilePath = destFilePath;
}
public void run(){
System.out.printf("Copying file '%s' to '%s'\n", srcFilePath, destFilePath);
}
}
public class MultiThreaded {
static String SRC = "C:\\src";
static String DST = "Z:\\dst";
static int FILECOUNT = 10000;
static List<String> getFilePathsInSource(String srcDirectory){
List<String> lst = new ArrayList<>();
String filePath = "";
for(int i=1;i<=FILECOUNT;i++){
filePath = String.join(File.separator, SRC, i+".txt");
lst.add(filePath);
}
return lst;
}
public static void main(String args[]) throws Exception{
List<String> files = getFilePathsInSource(SRC);
String destFilePath;
File srcFile;
CopyFileScheduler scheduler = new CopyFileScheduler();
long startTime = System.nanoTime();
for(String srcFilePath : files){
srcFile = new File(srcFilePath);
destFilePath = String.join(File.separator, DST, srcFile.getName());
MultiThreadedCopyFileTask cpt = new MultiThreadedCopyFileTask(srcFilePath, destFilePath);
scheduler.addTask(cpt);
}
scheduler.executeTasks();
long endTime = System.nanoTime();
long durationInNano = (endTime - startTime);
System.out.printf("TOTAL TIME TAKEN : %d nanoseconds\n", durationInNano);
System.out.printf("TOTAL TIME TAKEN : %d microseconds\n", durationInNano/1000);
System.out.printf("TOTAL TIME TAKEN : %d milliseconds\n", durationInNano/1000000);
}
}