code:
import java.io.*; import java.net.*; class Cassetto { private int contatore; public Cassetto(int val){ contatore = val; } public synchronized void produci(int incremento){ contatore = contatore + incremento; } public synchronized void consuma(int decremento){ if(contatore > decremento){ contatore = contatore - decremento; } else { contatore = 0; } } public int report(){ return contatore; } } class Produttore extends Thread{ static Cassetto cp; static ServerSocket ss; static Socket s; public Produttore(int porta, Cassetto c){ try{ cp = c; ss = new ServerSocket(porta); } catch (Exception e) {} } public void run(){ // Ogni 10 secondi il produttore incrementa... while(true){ try{ Thread.sleep(10000); } catch(Exception e) {} // il valore 10 può essere cambiato a piacere cp.produci(10); System.out.println("Produco! Ora siamo a "+ cp.report()); } } public static void main(String[] args){ Produttore p = new Produttore(12000,new Cassetto(400)); p.start(); try{ while(true){ s = ss.accept(); (new ClientManager(cp, s)).start(); } } catch(Exception e) {} } } class ClientManager extends Thread { Cassetto ccm; Socket scm; public ClientManager(Cassetto c, Socket s){ ccm = c; scm = s; } public void run(){ try { InputStream ThreadIn = scm.getInputStream(); OutputStream ThreadOut = scm.getOutputStream(); int c; // Legge dal client quanto bisogna consumare String valore = ""; while ((c = ThreadIn.read()) != 10) { valore = valore + (char)c; } // Consuma ccm.consuma(Integer.valueOf(valore).intValue()); System.out.println("Decremento di " + valore + ". Siamo a "+ ccm.report()); // Riporta al client il valore attuale valore = "" + ccm.report()+ '\n'; for (int i=0; i < valore.length(); i++) { ThreadOut.write((int)valore.charAt(i)); } } catch(Exception e) {} } } class Consumatore{ public static void main(String[] args){ Socket s; OutputStream ClientOut; InputStream ClientIn; int decremento = 20; try{ s = new Socket("localhost", 12000); ClientOut = s.getOutputStream(); ClientIn = s.getInputStream(); int c; String valore; // Comunica al server quanto bisogna consumare valore = "" + decremento + '\n'; for (int i=0; i < valore.length(); i++) { ClientOut.write((int)valore.charAt(i)); } System.out.println("Chiedo di decrementare di " + decremento); // Riceve dal server il valore attuale valore = ""; while ((c = ClientIn.read()) != 10) { valore = valore + (char)c; } System.out.println("Nel cassetto ci sono per ora " + valore); } catch(Exception e) { } } }