Created
January 30, 2012 17:40
-
-
Save Feder1co5oave/1705596 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author Feder1co 5oave | |
*/ | |
class Mailbox { | |
class Message { | |
Message next; | |
String text; | |
Message(String t) { | |
text = t; | |
// next = null | |
} | |
} | |
private static final int N = 4; | |
private Message[] heads, tails; | |
private Object[] monitors; | |
public Mailbox() { | |
heads = new Message[N]; | |
tails = new Message[N]; | |
monitors = new Object[N]; | |
for (int i = 0; i < N; i++) monitors[i] = new Object(); | |
} | |
public void invia(int tipo, String message) { | |
synchronized(monitors[tipo]) { | |
Message m = new Message(message); | |
if (heads[tipo] == null) { | |
heads[tipo] = tails[tipo] = m; | |
} else { | |
tails[tipo].next = m; | |
tails[tipo] = m; | |
} | |
monitors[tipo].notify(); // uno entra, uno esce | |
} | |
} | |
public String ricevi(int tipo) throws InterruptedException { | |
synchronized (monitors[tipo]) { | |
while (heads[tipo] == null) monitors[tipo].wait(); | |
Message ret = heads[tipo]; | |
if (ret.next == null) tails[tipo] = null; | |
heads[tipo] = ret.next; | |
return ret.text; | |
} | |
} | |
} | |
class Lettore extends Thread { | |
private Mailbox m; | |
private int t; | |
public Lettore(int tipo, Mailbox mailbox) { | |
m = mailbox; | |
t = tipo; | |
start(); | |
} | |
public void run() { | |
String msg = ""; | |
do { | |
try { | |
msg = m.ricevi(t); | |
System.out.println("Tipo " + t + ": " + msg); | |
} catch (InterruptedException ex) {} | |
} while (!msg.equals("Stop")); | |
} | |
} | |
class Scrittore extends Thread { | |
private Mailbox m; | |
private int t; | |
public Scrittore(int tipo, Mailbox mailbox) { | |
m = mailbox; | |
t = tipo; | |
start(); | |
} | |
public void run() { | |
int i = 0; | |
m.invia(t, "Messaggio " + (i++)); | |
m.invia(t, "Messaggio " + (i++)); | |
m.invia(t, "Messaggio " + (i++)); | |
m.invia(t, "Stop"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Pesa { | |
public static void main(String[] args) { | |
Mailbox m = new Mailbox(); | |
for (int i = 0; i < 3; i++) { | |
new Lettore(i, m); | |
new Scrittore(i, m); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment