timdebuyst

ZoekGetal.java

Mar 14th, 2019
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.96 KB | None | 0 0
  1. package hfdst4;
  2. import java.util.*;
  3.  
  4. class ZoekGetal extends Thread {
  5.     protected int startpositie;
  6.     protected int eindpositie;
  7.     protected int getal;
  8.     protected int[] rij;
  9.     protected ArrayList<Integer> resultaten;
  10.    
  11.     public ZoekGetal(int startpositie, int eindpositie, int getal, int[] rij, ArrayList<Integer> resultaten) {
  12.         this.startpositie = startpositie;
  13.         this.eindpositie = eindpositie;
  14.         this.getal = getal;
  15.         this.rij = rij;
  16.         this.resultaten = resultaten;
  17.     }
  18.    
  19.     public void run() {
  20.         for(int i = this.startpositie; i < this.eindpositie; i++) {
  21.             if(rij[i] == this.getal) {
  22.                 this.resultaten.add(i);
  23.             }
  24.             try {
  25.                 Thread.sleep(10);
  26.             } catch(InterruptedException e) {}
  27.         }
  28.     }
  29. }
  30.  
  31. class TestZoekGetal {
  32.     public static void main(String[] args) {
  33.         int aantalThreads = 8;
  34.         int N = 1000;
  35.         int m = 10;
  36.         ZoekGetal[] z = new ZoekGetal[aantalThreads];
  37.         ArrayList[] r = new ArrayList[aantalThreads];
  38.         int[] a = maakRij(N, m);
  39.         // added
  40.         int interval = N/aantalThreads;
  41.         //
  42.         for(int i=0;i<z.length;i++) {
  43.             r[i] = new ArrayList();
  44.             // z[i] = new ZoekGetal(0, N, 3, a, r[i]);
  45.             z[i] = new ZoekGetal(i*interval, (i+1)*interval, 3, a, r[i]); // added
  46.         }
  47.         for(int i=0;i<z.length;i++) {
  48.             z[i].start();
  49.         }
  50.         // added
  51.         /*
  52.         boolean done = false;
  53.         while(!done) {
  54.             done = true;
  55.             for (int i = 0; i < z.length; i++) {
  56.                 if (z[i].isAlive()) {
  57.                     done = false;
  58.                     break;
  59.                 }
  60.             }
  61.         }
  62.         */
  63.         // or
  64.         for (ZoekGetal zoek : z) {
  65.             try {
  66.                 zoek.join();
  67.             } catch(InterruptedException e) {
  68.                 e.printStackTrace();
  69.             }
  70.         }
  71.         //
  72.         for(int i=0;i<z.length;i++){
  73.             System.out.println(""+i+":"+r[i]);
  74.         }
  75.    }
  76.    public static int[] maakRij(int n, int m){
  77.        int[] r = new int[n];
  78.        for(int i=0;i<r.length;i++){
  79.            r[i] = (int)(m*Math.random());
  80.        }
  81.        return r;
  82.    }
  83. }
Add Comment
Please, Sign In to add comment