Java 코드 최적화
Pavlos Kosmetatos
Lead Engineer @Wealthyhood
어떻게 가능할까요?
싱글 스레딩은 자동차가 한 줄로 서서 차례대로 지나가야 하는 1차선 도로와 같습니다. 멀티스레딩은 여러 차선이 있어 자동차가 동시에 달릴 수 있는 것과 같습니다!
Thread 클래스를 사용하면 새로운 실행 경로를 만들 수 있습니다Thread는 독립적으로 실행될 수 있습니다Runnable 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 클래스Java 코드 최적화