package Multithreading.Max;
import java.util.ArrayList;
public class FindMax implements Runnable {
private static int max;
private Object lock = new Object();
private ArrayList<Integer> tab;
private int start, end;
public FindMax(ArrayList<Integer> tab, int start, int end) {
this.tab = tab;
this.start = start;
this.end = end;
max = tab.get(0);
}
@Override
public void run() {
for(int i = start; i<end; i++) {
// Synchronizacja - bardzo ważna rzecz
// gwarantuje że tylko jeden wątek na raz będzie mógł dostać się do maxa
// jak nie rozumiesz to ją wywal i zobacz co się stanie
synchronized (lock) {
if(tab.get(i)>max)
max = tab.get(i);
}
}
// pomocnicze wypisywanie podtablic - można wywalić
System.out.println(tab.subList(start, end));
}
public static int getMax() {
return max;
}
}
package Multithreading.Max;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n, w;
ArrayList<Integer> tab = new ArrayList<Integer>();
ArrayList<Thread> threadsTab = new ArrayList<Thread>();
Random rand = new Random();
Scanner input = new Scanner(System.in);
System.out.println("Podaj N");
n = input.nextInt();
System.out.println("Podaj W");
w = input.nextInt();
if(n<=0 || w<=0) {
System.out.println("N i W muszą być dodatnie");
return;
}
else if(n<w)
{
System.out.println("N musi byc wieksze od W");
return;
}
// delta - określa ilosc elementów w podtablicy
// rest - to reszta
int delta = n / w;
int rest = n % w;
// generowanie elementów
for(int i = 0; i<n; i++)
tab.add(rand.nextInt(10001));
// utworzenie W wątków
for(int i = 0; i<w; i++) {
if(i + 1 < w)
threadsTab.add(new Thread(new FindMax(tab, i*delta, delta + (i*delta))));
else
threadsTab.add(new Thread(new FindMax(tab, i*delta, delta + (i*delta) + rest)));
}
//wystartowanie wątków
for(Thread t : threadsTab)
t.start();
// oczekiwanie na zakończenie wszytkich wątków
for(Thread t : threadsTab) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(tab);
System.out.println(FindMax.getMax());
}
}
UWAGA!!! Dzielenie tablicy nie jest optymalne, po prostu daje resztę do ostatniego wątku.