Biblioteca Java - Blame information for rev 28

Subversion Repositories:
Rev:
Rev Author Line No. Line
28 mihai 1 package exemple.fire.barrier;
2  
3 /*
4  * The CyclicBarrier class allows you to create a barrier in one of two ways.
5  * You can create a barrier with a number of parties (threads), or with a
6  * number of parties and a barrier action. A barrier action is a Runnable task
7  * that executes when all the threads have joined together, but before the
8  * threads are released to run on their own.
9  *
10  * After each of the parties finishes its individual task, the party joins the
11  * barrier by calling its await method. This blocks that party until all parties
12  * are present. If a barrier action is provided, it then runs, before releasing
13  * all the parties.
14  */
15 import java.util.concurrent.*;  
16  
17 public class Summary {
18   private static int matrix[][] = {
19     {1},
20     {2, 2},
21     {3, 3, 3},
22     {4, 4, 4, 4},
23     {5, 5, 5, 5, 5}
24   };
25   private static int results[];  
26  
27   private static class Summer extends Thread {
28     int row;
29     CyclicBarrier barrier;
30     Summer(CyclicBarrier barrier, int row) {
31       this.barrier = barrier;
32       this.row = row;
33     }
34     public void run() {
35       int columns = matrix[row].length;
36       int sum = 0;
37       for (int i=0; i<columns; i++) {
38         sum += matrix[row][i];
39       }
40       results[row] = sum;
41       System.out.println(
42          "Results for row " + row + " are : " + sum);
43       // wait for others
44       try {
45         barrier.await();
46       } catch (InterruptedException ex) {
47         ex.printStackTrace();
48       } catch (BrokenBarrierException ex) {
49         ex.printStackTrace();
50       }
51  
52       System.out.println("thread "+this.getName()+" end");
53  
54     }
55   }
56  
57   public static void main(String args[]) {
58     final int rows = matrix.length;
59     results = new int[rows];
60     Runnable merger = new Runnable() {
61       public void run() {
62         int sum = 0;
63         for (int i=0; i<rows; i++) {
64           sum += results[i];
65         }
66         System.out.println("Results are: " + sum);
67       }
68     };
69     CyclicBarrier barrier = new CyclicBarrier(rows, merger);
70     for (int i=0; i<rows; i++) {
71       new Summer(barrier, i).start();
72     }
73     System.out.println("Waiting...");
74   }
75 }