Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.3 kB
4
Indexable
class MyThread extends Thread {
    int start,end,partialsum=0;
    MyThread(int start, int end){
        this.start=start;
        this.end=end;
    }
    public void run() {
        for(int i=start;i<=end;i++){
            partialsum+=i;
        }
        System.out.println(Thread.currentThread().getId()+" partial summation: "+partialsum);
        Task.sum+=partialsum;
        
    }
}
public class Task{
    public static int sum=0;
    public static void main(String[] args) {
        
        MyThread thread1 = new MyThread(1, 10000);
        MyThread thread2 = new MyThread(10001, 20000);
        MyThread thread3 = new MyThread(20001, 30000);
        MyThread thread4 = new MyThread(30001, 40000);
        MyThread thread5 = new MyThread(40001, 50000);
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
        
        try{
            thread1.join();
            thread2.join();
            thread3.join();
            thread4.join();
            thread5.join();
        }
        catch(Exception e){
            System.out.println("There's an error");
        }

        System.out.println("Grand sum: "+sum);
    }
}
Leave a Comment