This repository has been archived on 2023-06-18. You can view files and clone it, but cannot push or open issues or pull requests.
soft-an04/Reversal/src/main/java/ParallelReverser.java

65 lines
1.4 KiB
Java

import java.util.ArrayList;
class ParallelReverser extends ArrayReverser
{
// number of threads
private final int N;
// number of elements mapped by each thread
private final int S;
// reverse `array` using N threads
public ParallelReverser(int[] array, int N) {
setArray(array);
this.N = N;
this.S = array.length / this.N;
}
public void reverse() {
ArrayList<Thread> threads = new ArrayList<>();
for (int n = 0; n < N; n++) {
// thread t will reverse a[n*S..n*S + S]
int from = n*S;
int to = (n*S + S);
// the last thread takes what's left
if (n == N - 1)
to = array.length;
ThreadedReverser s = new ThreadedReverser(array, from, to, reversed);
Thread t = new Thread(s);
threads.add(t);
// start the thread
t.start();
}
// wait for all threads to terminate
for (int k = 0; k < threads.size(); k++) {
try {
Thread t = threads.get(k);
// wait for thread t to terminate
t.join();
} catch (InterruptedException s) {
System.out.println("Thread interrupted");
}
}
}
}
class ThreadedReverser extends SequentialReverser implements Runnable
{
private int from, to;
ThreadedReverser(int[] array, int from, int to, int[] result) {
super(array);
// reverse `array` into the given `result` array
this.reversed = result;
this.from = from;
this.to = to;
}
public void run() {
reverse(from, to);
}
}