Biblioteca Java - Blame information for rev 28

Subversion Repositories:
Rev:
Rev Author Line No. Line
28 mihai 1 package exemple.fire.semaphore;
2  
3 /*
4  * The wait-notify system in standard Java is not the only way that thread
5  * synchronization can be done. A classic approach in other languages is the
6  * semaphore, which is a protected variable allows up to a given N number of
7  * threads to access a resource simultaneously.
8  *
9  * Notice how the results for pass 0 and 1 don't appear until after many other
10  * results. You then get more 20s before seeing more "good" results. Each call
11  * to the average pricing service takes time, therefore the interspersed results.
12  *
13  * By going through a semaphore, the program effectively controls access to the
14  * limited resource.
15  */
16  
17 import java.util.concurrent.*;
18 import java.util.*;  
19  
20 public class SemaphoreTest {
21   private static final int LOOP_COUNT = 100;
22   private static final int MAX_AVAILABLE = 2;
23   private final static Semaphore semaphore =
24     new Semaphore(MAX_AVAILABLE, true);  
25  
26   private static class Pricer {
27     private static final Random random = new Random();
28     public static int getGoodPrice() {
29       int price = random.nextInt(100);
30       try {
31         Thread.sleep(50);
32       } catch (InterruptedException ex) {
33         ex.printStackTrace();
34       }
35       return price;
36     }
37     public static int getBadPrice() {
38       return 20;
39     }
40   }
41  
42   public static void main(String args[]) {
43     for (int i=0; i<LOOP_COUNT; i++) {
44       final int count = i;
45       new Thread() {
46         public void run() {
47           int price;
48          /* if (semaphore.tryAcquire()) {
49             try {
50  
51               price = Pricer.getGoodPrice();
52             } finally {
53               semaphore.release();
54             }
55           } else {
56             price = Pricer.getBadPrice();
57           }
58           */
59           try {
60                         semaphore.acquire();
61                 } catch (InterruptedException e) {
62                         // TODO Auto-generated catch block
63                         e.printStackTrace();
64                 }
65           price = Pricer.getGoodPrice();
66           semaphore.release();
67           System.out.println(count + ": " + price);
68         }
69       }.start();
70     }
71   }
72 }