Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ZonePartage extends Thread {
- int nLecteurs=0;
- int nEcrivainsEnAttente=0;
- Object accesslock;
- boolean exclusion=false;
- ZonePartage() {
- accesslock = new Object();
- }
- public void accesPartage() {
- synchronized(accesslock) {
- while(nEcrivainsEnAttente>0 && exclusion) attente();
- nLecteurs++;
- }
- }
- public void retourPartage() {
- synchronized(accesslock) {
- nLecteurs--;
- if(nLecteurs==0) accesslock.notifyAll();
- }
- }
- public void accesExclusif() {
- synchronized(accesslock) {
- exclusion=true;
- while(nLecteurs!=0 && nEcrivainsEnAttente>0) attente();
- nEcrivainsEnAttente++;
- }
- }
- public void retourExclusif() {
- synchronized(accesslock) {
- nEcrivainsEnAttente--;
- exclusion=false;
- accesslock.notifyAll();
- }
- }
- public void attente() {
- try {
- accesslock.wait(); // bloque jusqu'a un notify()
- } catch(InterruptedException e) {};
- }
- }
- class Reader extends Thread {
- ZonePartage z;
- String name;
- Reader (ZonePartage z, String name) {
- super(name);
- this.z = z;
- this.name=name;
- }
- public void run() {
- while (true) {
- lecture();
- }
- }
- public void lecture() {
- z.accesPartage();
- System.out.println("" +name +" Lecture (lecteur=" +z.nLecteurs +" / ecrivain=" +z.nEcrivainsEnAttente +")");
- z.retourPartage();
- }
- }
- class Writer extends Thread {
- ZonePartage z;
- String name;
- Writer (ZonePartage z, String name) {
- super(name);
- this.z = z;
- this.name=name;
- }
- public void run() {
- while (true) {
- ecriture();
- }
- }
- public void ecriture() {
- z.accesExclusif();
- System.out.println("" +name +" Ecriture (lecteur=" +z.nLecteurs +" / ecrivain=" +z.nEcrivainsEnAttente +")");
- z.retourExclusif();
- }
- }
- public class LectEcrivain {
- public static void main(String args[]) {
- ZonePartage z = new ZonePartage();
- Thread r1 = new Reader(z,"r1");
- Thread r2 = new Reader(z,"r2");
- Thread r3 = new Reader(z,"r3");
- Thread r4 = new Reader(z,"r4");
- Thread w1 = new Writer(z,"w1");
- Thread w2 = new Writer(z,"w2");
- r1.start();
- r2.start();
- r3.start();
- r4.start();
- w1.start();
- w2.start();
- }
- }
Add Comment
Please, Sign In to add comment