Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class MyThread implements Runnable {
- private final int id;
- int start, end;
- public MyThread(int id) {
- this.id = id;
- }
- public int min(int a, int b) {
- if (a < b) {
- return a;
- } else {
- return b;
- }
- }
- @Override
- public void run() {
- start = (int)(id * Main.chunk_size);
- end = min((int)((id + 1) * Main.chunk_size), Main.N);
- System.out.println("Thread " + id + " calculeaza de la " + start + " la " + end);
- for (int i = start; i < end; i++) {
- Main.v[i] = Main.v[i] * 2;
- }
- //System.out.println("Salut de pe threadul #" + id);
- }
- }
- public class Main {
- static int N = 1007;
- static int nThreads = 4;
- static int v[] = new int[N];
- public static double chunk_size = (double) N / nThreads;
- public static void main(String[] args) {
- Thread[] threads = new Thread[nThreads];
- for (int i = 0; i < N; i++)
- v[i] = i;
- for (int i = 0; i < nThreads; i++) {
- threads[i] = new Thread(new MyThread(i));
- threads[i].start();
- }
- for (int i = 0; i < nThreads; i++) {
- try {
- threads[i].join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- for (int i = 0; i < N; i++) {
- if (v[i] != i * 2) {
- System.out.println("Wrong answer");
- System.out.println(v[i] + " is different than " + i * 2);
- System.exit(1);
- }
- }
- System.out.println("Correct");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement