source: trunk/PCSem.java@ 12

Last change on this file since 12 was 2, checked in by Mattia Monga, 14 years ago

Importazione sorgenti

File size: 2.7 KB
Line 
1/**
2 * Describe class PC here.
3 *
4 *
5 * Created: Fri Jun 8 14:32:29 2007
6 *
7 * @author <a href="mailto:mattia.monga@unimi.it">Mattia Monga</a>
8 * @version 1.0
9 */
10
11import java.util.concurrent.Semaphore;
12
13class Actor extends Thread
14{
15 public Actor(String nome){
16 super(nome);
17 }
18
19 private Magazzino shared;
20 public final Magazzino getShared() {
21 return shared;
22 }
23 public final void setShared(final Magazzino newShared) {
24 this.shared = newShared;
25 }
26
27}
28
29
30class Produttore extends Actor {
31 public Produttore(String nome, Magazzino b) {
32 super(nome);
33 setShared(b);
34 }
35
36 public void run(){
37 int i = 0;
38 while(true){
39 System.out.println(getName() + ": Inserisco " + i + " nel buffer");
40 getShared().put(i);
41 i += 1;
42 }
43 }
44}
45
46class Consumatore extends Actor{
47 public Consumatore(String nome, Magazzino b) {
48 super(nome);
49 setShared(b);
50 }
51 public void run(){
52 while(true){
53 int i = getShared().get();
54 System.out.println(getName() + ": Estraggo " + i + " dal buffer");
55
56 }
57 }
58}
59
60class Magazzino{
61 public final static int SIZE = 10;
62 private int[] memory = new int[SIZE];
63 private int quanti = 0;
64
65 public final int get() {
66 try{
67 String n = Thread.currentThread().getName();
68 pieno.acquire();
69 mutex.acquire();
70 int ris = memory[--quanti];
71 mutex.release();
72 vuoto.release();
73
74 System.out.println(n + " ha letto");
75 return ris;
76 }
77 catch(InterruptedException e){
78 System.err.println(e);
79 return -1;
80 }
81 }
82
83 public final void put(final int newMemory) {
84 try{
85 String n = Thread.currentThread().getName();
86 vuoto.acquire();
87 mutex.acquire();
88 memory[quanti++] = newMemory;
89 mutex.release();
90 pieno.release();
91 System.out.println(n + " ha scritto");
92 }
93 catch(InterruptedException e){
94 System.err.println(e);
95 }
96 }
97
98 private static final Semaphore mutex = new Semaphore(1);
99 private static final Semaphore pieno = new Semaphore(0);
100 private static final Semaphore vuoto = new Semaphore(SIZE);
101
102}
103
104
105public class PCSem {
106
107 public static final void main(final String[] args) {
108 Magazzino x = new Magazzino();
109 Produttore a1 = new Produttore("Aldo", x);
110 Produttore a2 = new Produttore("Alberto", x);
111 Consumatore b = new Consumatore("Barbara", x);
112 a1.start();
113 b.start();
114 a2.start();
115 }
116
117}
Note: See TracBrowser for help on using the repository browser.