public class Giocatore extends Thread {
private String nome;
private int attesa = 1; // in secondi
private Finestra finestra;
private int totale = 0;
private int massimo = 100;
public Giocatore(String nome, int attesa) {
this.nome = nome;
this.attesa = attesa;
}
public Giocatore(String nome, int attesa, Finestra finestra) {
this.nome = nome;
this.attesa = attesa;
this.finestra = finestra;
}
public Giocatore(String nome, int attesa, Finestra finestra, int massimo) {
this.nome = nome;
this.attesa = attesa;
this.finestra = finestra;
this.massimo = massimo;
}
public String getNome() {
return nome;
}
public int getAttesa() {
return attesa;
}
public int getMassimo() {
return massimo;
}
@Override
public void run() {
while(totale < massimo) {
try {
Random r = new Random();
int v = r.nextInt(11)+2;
System.out.println("thread "+ nome +", valore "+ v +", totale "+ totale);
finestra.stampa("thread "+ nome +", valore "+ v +", totale "+ totale);
totale = totale + v;
if (totale >= massimo) finestra.setVittoria(nome);
sleep(attesa * 1000);
} catch (InterruptedException ex) {
Logger.getLogger(Giocatore.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class Finestra extends javax.swing.JFrame {
private ArrayList<Giocatore> lista = new ArrayList<>();
private boolean vittoria = false;
/**
* Creates new form Finestra
*/
public Finestra() {
initComponents();
}
public synchronized void stampa(String txt) {
txtArea.append(txt+"\n");
}
public synchronized boolean setVittoria(String txt) {
boolean ret = false;
if (!vittoria) {
vittoria = true;
ret = true;
stampa(txt + " ha vinto!");
}
else ret = false;
return ret;
}
private void btnEsciActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void btnAvviaActionPerformed(java.awt.event.ActionEvent evt) {
int num = Integer.parseInt(spnNumGiocatori.getValue().toString());
int max = Integer.parseInt(cmbMassimo.getSelectedItem().toString());
txtArea.selectAll();
txtArea.replaceSelection("");
for(int i=0; i < num; i++) {
Giocatore g = new Giocatore("Giovatore "+ (i+1), 1, this, max);
lista.add(g);
g.start();
}
}
private void btnChiudiActionPerformed(java.awt.event.ActionEvent evt) {
for(int i=0; i < lista.size(); i++) {
lista.get(i).stop();
}
}
// Variables declaration - do not modify
private javax.swing.JButton btnAvvia;
private javax.swing.JButton btnChiudi;
private javax.swing.JButton btnEsci;
private javax.swing.JComboBox<String> cmbMassimo;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSpinner spnNumGiocatori;
private javax.swing.JTextArea txtArea;
// End of variables declaration
}