Sobes.tech
Senior

Have you ever applied threading in practice? Can you give an example of a task?

sobes.tech AI

Answer from AI

Yes, in Java practice I often use Threads for parallel task processing, especially when I need to perform multiple operations simultaneously or handle data asynchronously.

Example task: processing a large data array using multiple threads to speed up calculations.

public class ParallelSum {
    public static void main(String[] args) throws InterruptedException {
        int[] data = new int[1000000];
        // Fill the array
        for (int i = 0; i < data.length; i++) {
            data[i] = i + 1;
        }

        // Create two threads to calculate the sum
        SumThread t1 = new SumThread(data, 0, data.length / 2);
        SumThread t2 = new SumThread(data, data.length / 2, data.length);

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        int totalSum = t1.getSum() + t2.getSum();
        System.out.println("Total sum: " + totalSum);
    }
}

class SumThread extends Thread {
    private int[] data;
    private int start, end;
    private int sum = 0;

    public SumThread(int[] data, int start, int end) {
        this.data = data;
        this.start = start;
        this.end = end;
    }

    public void run() {
        for (int i = start; i < end; i++) {
            sum += data[i];
        }
    }

    public int getSum() {
        return sum;
    }
}

This approach allows efficient use of CPU resources and speeds up processing.