Optymalizacja kodu w Javie
Pavlos Kosmetatos
Lead Engineer @Wealthyhood
Jak to działa?
Jednowątkowość przypomina jednopasową drogę, po której samochody jadą jeden za drugim. Wielowątkowość to wielopasmowa autostrada, gdzie samochody jadą jednocześnie!
Thread umożliwia tworzenie nowych ścieżek wykonaniaThread może działać niezależnieRunnable task = () -> {
System.out.println("Processing on thread: " +
Thread.currentThread().getName());
};
Thread thread = new Thread(task);
thread.start();
Processing on thread: Thread-0
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < 4; i++) {
Thread thread = new Thread(() -> System.out.println("Processing data on Thread-" + i));
threads.add(thread);
thread.start();
}
for (Thread t : threads) {
t.join(); // Waits for all threads to complete
}
// Processing data on Thread-0
// Processing data on Thread-2
// Processing data on Thread-1
// Processing data on Thread-3
collection.parallelStream()Stream.of(...).parallel()// Sequential processing List<Integer> result1 = new ArrayList<>(); for (int i = 0; i < numbers.size(); i++) { result1.add(numbers.get(i) * 2); }// Sequential processing with stream List<Integer> result2 = numbers.stream() .map(n -> n * 2) .collect(Collectors.toList());// Parallel processing with parallel stream List<Integer> result3 = numbers.parallelStream() .map(n -> n * 2) .collect(Collectors.toList());
Thread do tworzenia równoległych ścieżek wykonaniaOptymalizacja kodu w Javie