source: trunk/PC.java@ 20

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

Importazione sorgenti

File size: 2.9 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
11class Actor extends Thread
12{
13 public Actor(String nome){
14 super(nome);
15 }
16
17 private Magazzino shared;
18 public final Magazzino getShared() {
19 return shared;
20 }
21 public final void setShared(final Magazzino newShared) {
22 this.shared = newShared;
23 }
24
25}
26
27
28class Produttore extends Actor {
29 public Produttore(String nome, Magazzino b) {
30 super(nome);
31 setShared(b);
32 }
33
34 public void run(){
35 int i = 0;
36 while(true){
37 System.out.println(getName() + ": Inserisco " + i + " nel buffer");
38 getShared().put(i);
39 i += 1;
40 }
41 }
42}
43
44class Consumatore extends Actor{
45 public Consumatore(String nome, Magazzino b) {
46 super(nome);
47 setShared(b);
48 }
49 public void run(){
50 while(true){
51 int i = getShared().get();
52 System.out.println(getName() + ": Estraggo " + i + " dal buffer");
53
54 }
55 }
56}
57
58class Magazzino{
59 public final static int SIZE = 10;
60 private int[] memory = new int[SIZE];
61 private int quanti = 0;
62
63 public final int get() {
64 String n = Thread.currentThread().getName();
65 synchronized(syncPC){
66 while(isVuoto()){
67 System.out.println(n + " ha tentato di leggere");
68 try {
69 syncPC.wait();
70 } catch (InterruptedException e) {
71 System.err.println(e);
72 }
73 }
74 int ris = memory[--quanti];
75 if (quanti == SIZE - 1) syncPC.notifyAll();
76 System.out.println(n + " ha letto");
77 return ris;
78 }
79 }
80
81 public final void put(final int newMemory) {
82 String n = Thread.currentThread().getName();
83 synchronized(syncPC){
84 while (isPieno()){
85 System.out.println(n + " ha tentato di scrivere");
86 try {
87 syncPC.wait();
88 } catch (InterruptedException e) {
89 e.printStackTrace(System.err);
90 }
91 }
92 memory[quanti++] = newMemory;
93 if (quanti == 1) syncPC.notifyAll();
94 System.out.println(n + " ha scritto");
95 }
96 }
97
98 public final boolean isVuoto() {
99 return quanti == 0;
100 }
101
102 public final boolean isPieno() {
103 return quanti == SIZE;
104 }
105
106 private Object syncPC = new Object();
107}
108
109
110public class PC {
111
112 public static final void main(final String[] args) {
113 Magazzino x = new Magazzino();
114 Produttore a1 = new Produttore("Aldo", x);
115 Produttore a2 = new Produttore("Alberto", x);
116 Consumatore b = new Consumatore("Barbara", x);
117 a1.start();
118 b.start();
119 a2.start();
120 }
121
122}
123
124
Note: See TracBrowser for help on using the repository browser.