Advertisement
Irod

Untitled

Nov 24th, 2020
757
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.70 KB | None | 0 0
  1. class MyThread implements Runnable {
  2.     private final int id;
  3.     int start, end;
  4.  
  5.     public MyThread(int id) {
  6.         this.id = id;
  7.     }
  8.  
  9.     public int min(int a, int b) {
  10.         if (a < b) {
  11.             return a;
  12.         } else {
  13.             return b;
  14.         }
  15.     }
  16.  
  17.     @Override
  18.     public void run() {
  19.         start = (int)(id * Main.chunk_size);
  20.         end = min((int)((id + 1) * Main.chunk_size), Main.N);
  21.        
  22.         System.out.println("Thread " + id + " calculeaza de la " + start + " la " + end);
  23.        
  24.         for (int i = start; i < end; i++) {
  25.             Main.v[i] = Main.v[i] * 2;
  26.         }
  27.         //System.out.println("Salut de pe threadul #" + id);
  28.     }
  29.  
  30. }
  31.  
  32. public class Main {
  33.     static int N = 1007;
  34.     static int nThreads = 4;
  35.     static int v[] = new int[N];
  36.     public static double chunk_size = (double) N / nThreads;
  37.  
  38.  
  39.     public static void main(String[] args) {
  40.  
  41.         Thread[] threads = new Thread[nThreads];
  42.  
  43.         for (int i = 0; i < N; i++)
  44.             v[i] = i;
  45.  
  46.  
  47.         for (int i = 0; i < nThreads; i++) {
  48.             threads[i] = new Thread(new MyThread(i));
  49.             threads[i].start();
  50.         }
  51.  
  52.         for (int i = 0; i < nThreads; i++) {
  53.             try {
  54.                 threads[i].join();
  55.             } catch (InterruptedException e) {
  56.                 e.printStackTrace();
  57.             }
  58.         }
  59.  
  60.         for (int i = 0; i < N; i++) {
  61.             if (v[i] != i * 2) {
  62.                 System.out.println("Wrong answer");
  63.                 System.out.println(v[i] + " is different than " + i * 2);
  64.                 System.exit(1);
  65.             }
  66.         }
  67.         System.out.println("Correct");
  68.     }
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement