Biblioteca Java - Rev 3
Subversion Repositories:
/*
* SemaforTest.java
*/
package lab.scd.fire.semafor;
import java.util.concurrent.Semaphore;
/**
* Class created by @author Mihai HULEA at Feb 27, 2005.
*
* This class is part of the laborator1_fire_executie project.
*
* Testeaza folosirea clasei Semaphor din cadrul pachetului java.util.concurrent
*
* 1. Executati programul si analizati modul de functionare.
*
* 2. Eliminati comentariile din cadrul metodei useResource() si explicati diferentele
* in functionare.
*
* 3. In cadrul clasei Resource construiti semaforul folosind ca argument valoarea 2.
* Rulati si explicati modul de functionare.
*/
public class SemaforTest {
public static void main(String[] args) {
Resource res = new Resource();
User u1 = new User(res);
User u2 = new User(res);
User u3 = new User(res);
User u4 = new User(res);
}
}
class Resource{
/**
* Constuieste un semafor binar.
*/
Semaphore s = new Semaphore(1);
int simultanUsers = 0;
public void useResource(){
/* try {
s.acquire();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
*/
simultanUsers++;
try{Thread.sleep(200);}catch(Exception e){}
System.out.println("Resursa este utilizata "+simultanUsers);
simultanUsers--;
/*
s.release();
*/
}
}
class User extends Thread {
Resource res;
/**
* @param res
*/
public User(Resource res) {
this.res = res;
start();
}
public void run(){
int i=10;
while(i>0){
res.useResource();
i--;
}
}
}
* SemaforTest.java
*/
package lab.scd.fire.semafor;
import java.util.concurrent.Semaphore;
/**
* Class created by @author Mihai HULEA at Feb 27, 2005.
*
* This class is part of the laborator1_fire_executie project.
*
* Testeaza folosirea clasei Semaphor din cadrul pachetului java.util.concurrent
*
* 1. Executati programul si analizati modul de functionare.
*
* 2. Eliminati comentariile din cadrul metodei useResource() si explicati diferentele
* in functionare.
*
* 3. In cadrul clasei Resource construiti semaforul folosind ca argument valoarea 2.
* Rulati si explicati modul de functionare.
*/
public class SemaforTest {
public static void main(String[] args) {
Resource res = new Resource();
User u1 = new User(res);
User u2 = new User(res);
User u3 = new User(res);
User u4 = new User(res);
}
}
class Resource{
/**
* Constuieste un semafor binar.
*/
Semaphore s = new Semaphore(1);
int simultanUsers = 0;
public void useResource(){
/* try {
s.acquire();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
*/
simultanUsers++;
try{Thread.sleep(200);}catch(Exception e){}
System.out.println("Resursa este utilizata "+simultanUsers);
simultanUsers--;
/*
s.release();
*/
}
}
class User extends Thread {
Resource res;
/**
* @param res
*/
public User(Resource res) {
this.res = res;
start();
}
public void run(){
int i=10;
while(i>0){
res.useResource();
i--;
}
}
}