ciao a tutti sto facendo un esercizio sulla programmazione multithread e non capisco un errore del compilatore
ecco il codice
codice:
package esercizio2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/*
* 2. Esercizio (Somma) Scrivere un programma multithread in Java che esegue una funzione di somma tra
due numeri interi inseriti dall’utente. Creare un thread separato per effettuare la somma e restituire il
risultato in una variabile intera (globale) condivisa con il thread principale. Il thread principale deve
sincronizzarsi sulla terminazione (join) del thread figlio Somma e stampare poi il risultato a video.
[Suggerimento: Per la variabile condivisa, creare una classe involucro HoldInteger con dei metodi get/set.]
*/
public class MyThread implements Runnable {
private int valore1;
private int valore2;
private HoldInteger somma;
public MyThread(int valore1, int valore2, HoldInteger somma) {
super();
this.valore1 = valore1;
this.valore2 = valore2;
this.somma = somma;
}
@Override
public void run() {
somma.setI(valore1 + valore2);
}
public class HoldInteger {
private int i;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
public static void main(String[] args) {
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
HoldInteger somma = new HoldInteger();
try {
int valore1 = Integer.parseInt(input.readLine());
int valore2 = Integer.parseInt(input.readLine());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread t = new Thread(new MyThread(valore1, valore2, somma));
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(somma.getI());
}
}
l' errore è alla riga
codice:
Thread t = new Thread(new MyThread(valore1, valore2, somma));
e dice
Cannot make a static reference to the non-static field valore1
e altri errori... di java conosco la programmazione basa e non capisco perchè dovrebbe essere static ..