I have a txt file: order_me.txt
, in which there are some integers which need to be sorted using 4 threads. They need to work simultaneously, but not do the same thing. I have managed to sort the integers, but something is not working right...
This is the thread class:
public class Threading {
static List<Integer> integersCopy = new ArrayList<>();
public static void main(String[] args) {
openFile();
Thread t1 = new Thread(new Command("thread 1", integersCopy));
t1.start();
Thread t2 = new Thread(new Command("thread 2", integersCopy));
t2.start();
Thread t3 = new Thread(new Command("thread 3", integersCopy));
t3.start();
Thread t4 = new Thread(new Command("thread 4", integersCopy));
t4.start();
try {
if (t1.isAlive())
t1.join();
if (t2.isAlive())
t2.join();
if (t3.isAlive())
t3.join();
if (t4.isAlive())
t4.join();
} catch (Exception e) {
System.out.println("Exception with threads");
}
}
public static void openFile() {
File file = new File("order_me.txt");
try {
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
integersCopy = integers;
System.out.println("File opened successfully");
} catch (Exception e) {
System.out.println("Triggered exception");
}
}
And this is the sorting class:
import java.util.Collections;
import java.util.List;
public class Command implements Runnable {
String threadName;
List<Integer> listOfInts;
Command(String name, List<Integer> list) {
threadName = name;
listOfInts = list;
}
@Override
public void run() {
for (int i = 0; i < listOfInts.size(); i++) {
Collections.sort(listOfInts);
System.out.print(+listOfInts.get(i) + " ");
}
}
}