ciao ragazzi,
ho il seguente codice:
codice:
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
public class GestoreSerbatoio implements Runnable{
private int porta1;
private int porta2;
private int esig_totale;
private Socket clientsock;
public Integer esigenza_totale
private ConcurrentHashMap<Integer,Integer> utenti;
public GestoreSerbatoio(int porta1,int porta2)
{
this.porta1=porta1;
this.porta2=porta2;
utenti=new ConcurrentHashMap<Integer,Integer>();
esigenza_totale=new Integer(0);
}
public void run()
{
Integer id_utente;
Integer richiesta_utente;
try{
ServerSocket ss = new ServerSocket(porta1);
while(true)
{
clientsock=ss.accept();
ThreadUtenti tu = new
ThreadUtenti(clientsock,utenti,esigenza_totale);
System.out.println("variabile condivisa: " + esigenza_totale);
Thread t = new Thread(tu);
t.start();
}
}catch(Exception e){
System.err.println(e.getMessage());
}
}
}
codice:
public class ThreadUtenti implements Runnable{
private Socket s;
private ConcurrentHashMap<Integer,Integer> utenti;
static Integer esig_totale;
public ThreadUtenti(Socket s,ConcurrentHashMap<Integer,Integer> utenti,Integer esig_totale)
{
this.s=s;
this.utenti=utenti;
this.esig_totale=esig_totale;
}
public void run()
{
Integer id_utente=0;
Integer richiesta_utente=0;
try{
ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream is = new ObjectInputStream(s.getInputStream());
id_utente=(Integer)is.readObject();
richiesta_utente=(Integer)is.readObject();
esig_totale=esig_totale+richiesta_utente;
utenti.put(id_utente,richiesta_utente);
System.out.println("utente:" + id_utente + " richiesta: " + richiesta_utente + "esigenza totale: " + esig_totale);
s.close();
is.close();
os.close();
}catch(Exception e){
System.err.println(e.getMessage());
}
}
}
il problema è che la variabile non è condivisa bene, perchè se avvio il programma e lo eseguo man mano che sporco la variabile che passo al costruttore vale sempre zero.
qualcuno sa dirmi il perchè ?come posso fare?
grazie anticipatamente