Allora, questa è la classe produttore
public class Producer implements Runnable{
private int delay;
private Urna buffer;
public Producer (Urna buffer,int delay ){
this.delay=delay;
this.buffer=buffer;
}
public void run() {
for(int i=0;i<5;i++){
int k = (int) ((Math.random() * 89) +1);
//System.out.println(k);
buffer.add(k);
try {
Thread.sleep(((int)Math.random()*delay*300)+300);
}catch (InterruptedException ex){
ex.getMessage();
}
}
}
}
questa consumatore
public class Consumer implements Runnable{
private int delay;
private Urna buffer;
public int [] resto = new int[5];
public Consumer (Urna buffer,int delay ){
this.delay=delay;
this.buffer=buffer;
}
public void run() {
for(int i=0;i<5;i++){
int info = buffer.remove();
System.out.println(info);
resto[i]=info;
try {
Thread.sleep(delay);
}catch (InterruptedException ex){
ex.getMessage();
}
}
}
public String toString(){
String str = new String();
for(int k=0;k<5;k++)
str = str+ (k+1) + "Estratto : " + resto[k] +"\n";
return str;
}
}
Per poter scrivere sulla JText, ho pensato di fare 1 array metterci i dati "consumati" re-implemetare il metodo toString() e passare la stringa alla setText() per scrivere il risultato... ma il risultato ottenuto non è quello desiderato e cioè :
Essendo questa la classe dell'interfaccia:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Gui extends JFrame{
public JButton bottone;
public JTextField jTextField1;
public Gui(){
bottone = new JButton("ESTRAZIONE DEL LOTTO");
jTextField1 = new JTextField();
}
public void init(){
getContentPane().setLayout(new GridLayout());
getContentPane().add(bottone);
getContentPane().add(jTextField1);
jTextField1.setFocusable(false);
bottone.addActionListener ( new java.awt.event.ActionListener () {
public void actionPerformed ( ActionEvent e ) {
Urna u = new Urna(5);
Producer p = new Producer(u,1);
Consumer c = new Consumer(u,1);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
jTextField1.setText(c.toString());
}
}) ;
}
}
visto che richiamo il metodo toString sul consumatore il risultato è sempre 0 cioè è come se viene prima stampato il risultato e poi fatto partire il thread...
NON SO PROPRIO COME FARE (SARO' IMBECILLE, MA CMQ NN CI RIESCO)!!!!!
@ildiabolico
ps vado dal dentista spero che con il dolore mi venga qualche illuminazione