Biblioteca Java - Blame information for rev 28
Subversion Repositories:
Rev | Author | Line No. | Line |
---|---|---|---|
28 | mihai | 1 | /* |
2 | * SemaforTest.java | ||
3 | */ | ||
4 | package exemple.fire.semafor; | ||
5 | |||
6 | import java.util.concurrent.Semaphore; | ||
7 | |||
8 | /** | ||
9 | * Class created by @author Mihai HULEA at Feb 27, 2005. | ||
10 | * | ||
11 | * This class is part of the laborator1_fire_executie project. | ||
12 | * | ||
13 | * Testeaza folosirea clasei Semaphor din cadrul pachetului java.util.concurrent | ||
14 | * | ||
15 | * 1. Executati programul si analizati modul de functionare. | ||
16 | * | ||
17 | * 2. Eliminati comentariile din cadrul metodei useResource() si explicati diferentele | ||
18 | * in functionare. | ||
19 | * | ||
20 | * 3. In cadrul clasei Resource construiti semaforul folosind ca argument valoarea 2. | ||
21 | * Rulati si explicati modul de functionare. | ||
22 | */ | ||
23 | public class SemaforTest { | ||
24 | |||
25 | public static void main(String[] args) { | ||
26 | Resource res = new Resource(); | ||
27 | |||
28 | User u1 = new User(res); | ||
29 | User u2 = new User(res); | ||
30 | User u3 = new User(res); | ||
31 | User u4 = new User(res); | ||
32 | } | ||
33 | } | ||
34 | |||
35 | class Resource{ | ||
36 | /** | ||
37 | * Constuieste un semafor binar. | ||
38 | */ | ||
39 | Semaphore s = new Semaphore(1); | ||
40 | |||
41 | int simultanUsers = 0; | ||
42 | |||
43 | public void useResource(){ | ||
44 | |||
45 | /* try { | ||
46 | s.acquire(); | ||
47 | } catch (InterruptedException e1) { | ||
48 | e1.printStackTrace(); | ||
49 | } | ||
50 | */ | ||
51 | |||
52 | simultanUsers++; | ||
53 | |||
54 | try{Thread.sleep(200);}catch(Exception e){} | ||
55 | System.out.println("Resursa este utilizata "+simultanUsers); | ||
56 | |||
57 | simultanUsers--; | ||
58 | |||
59 | /* | ||
60 | s.release(); | ||
61 | */ | ||
62 | } | ||
63 | } | ||
64 | |||
65 | class User extends Thread { | ||
66 | Resource res; | ||
67 | |||
68 | /** | ||
69 | * @param res | ||
70 | */ | ||
71 | public User(Resource res) { | ||
72 | this.res = res; | ||
73 | start(); | ||
74 | } | ||
75 | |||
76 | public void run(){ | ||
77 | int i=10; | ||
78 | while(i>0){ | ||
79 | res.useResource(); | ||
80 | i--; | ||
81 | } | ||
82 | } | ||
83 | } | ||
84 |