Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Scanner;
- import java.util.concurrent.Semaphore;
- public class Philosophe extends Thread {
- static int nb;
- Fourchette f1;
- Fourchette f2;
- Table t;
- int id;
- public Philosophe(Fourchette f1, Fourchette f2, Table t) {
- this.f1 = f1;
- this.f2 = f2;
- this.id = nb++;
- this.t = t;
- }
- public void reflechir() {
- while (!f1.tryAcquire()) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- while (!f2.tryAcquire()) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- public void manger() {
- try {
- if (!t.manger()) {
- System.out.println("Plus d'assietes !");
- this.interrupt();
- } else {
- Thread.sleep(500);
- f1.release();
- f2.release();
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- public void dormir() {
- try {
- Thread.sleep((long) (Math.random() * 5000));
- } catch (InterruptedException e) {
- }
- }
- public Fourchette getFourchette1() {
- return f1;
- }
- public Fourchette getFourchette2() {
- return f2;
- }
- public void run() {
- while (true) {
- System.out.println("P" + id + ": reflechi");
- reflechir();
- System.out.println("P" + id + ": mange");
- manger();
- System.out.println("P" + id + ": dors");
- dormir();
- }
- }
- public static void main(String[] a) {
- int nbAssietes = 500;
- int nbPhilosophes = 0;
- if (nbPhilosophes < 2) {
- do {
- Scanner sc = new Scanner(System.in);
- try {
- nbPhilosophes = Integer.parseInt(sc.nextLine());
- } catch (Exception e) {
- }
- } while (nbPhilosophes < 2);
- }
- if (nbAssietes < nbPhilosophes) {
- do {
- Scanner sc = new Scanner(System.in);
- try {
- nbAssietes = Integer.parseInt(sc.nextLine());
- } catch (Exception e) {
- }
- } while (nbAssietes < nbPhilosophes);
- }
- Table t = new Table(nbAssietes);
- Fourchette f1 = new Fourchette();
- Fourchette fo = f1;
- Fourchette f2 = new Fourchette();
- ArrayList<Philosophe> philos = new ArrayList<Philosophe>();
- for (int i = 0; i < nbPhilosophes; i++) {
- f1 = f2;
- if (i == nbPhilosophes - 1)
- f2 = fo;
- else
- f2 = new Fourchette();
- Philosophe p = new Philosophe(f1, f2, t);
- philos.add(p);
- philos.get(i).start();
- }
- }
- }
- class Fourchette extends Semaphore {
- public Fourchette() {
- super(1, true);
- }
- }
- class Table {
- int nbAssietes;
- public Table(int assietes) {
- this.nbAssietes = assietes;
- }
- public boolean manger() {
- if (this.nbAssietes <= 0)
- return false;
- this.nbAssietes--;
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement