j'ai écrit un programme mulithreadé en java pour rechercher un élément dans un vecteur non trié.
mon programme utilise le framework Executor.
voici mon essai:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
 
 
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
public class SearchParallel {
 
    int[] array;
    Random r;
    int x, index = -1;
    ExecutorService pool;
 
    public SearchParallel(int length, int x) {
        this.x = x;
        pool = Executors.newCachedThreadPool();
        array = new int[length];
        r = new Random();
        for (int i = 0; i < array.length; i++) {
            array[i] = r.nextInt(length);
        }
    }
 
    class Worker implements Runnable {
 
        int start, end;
 
        public Worker(int start, int end) {
            this.start = start;
            this.end = end;
        }
 
        @Override
        public void run() {
 
            while (index == -1 && start < end) {
                if (array[start] != x) {
                    start++;
                } else {
                    index = start;
                    System.out.println(Thread.currentThread().getName());
                }
            }
 
        }
    }
 
    void display() {
        for (int i : array) {
            System.out.print(i + " ");
        }
        System.out.println();
 
    }
 
    void go(int n) {
        for (int k = 0; k < n; k++) {
            Worker w = new Worker(k * array.length / n, (k + 1) * array.length / n);
            pool.execute(w);
        }
        pool.shutdown();
        while (index == -1 && !pool.isTerminated()) {
        }
        if (index != -1) {
            System.out.println("item " + x + " is found at index " + index);
        } else {
            System.out.println("item " + x + "is not found");
        }
    }
 
    public static void main(String[] args) {
        int nbrTask = 10;
        SearchParallel sp = new SearchParallel(100, 4);
        sp.display();
        sp.go(nbrTask);
 
    }
 
}
normalement ce programme fonctionne mais j'aimerais profiter de votre expérience pour l’améliorer. si vous avez des remarques ou autres idées je suis très reconnaissant