Salve, sto avendo dei problemi nella creazione di un semplice programmino per la gestione di thread, non riesco a risolvere per via di un errore di NullPointerException in riga 61 e 80
codice:
public class prova { public static void main(String[] args){
Shared n = new Shared();
Thread_I a = new Thread_I();
Thread_D b = new Thread_D();
Thread tI = new Thread(a,"tI");
Thread tD = new Thread(b,"tD");
tI.start();
tD.start();
}
}
class Shared {
private int n = 100;
public synchronized boolean somma(int incremento){
String threadName = Thread.currentThread().getName();
n+=incremento;
System.out.println(threadName + "valore di n = "+n);
if(n>150){
System.out.println("Fine del thread! " + threadName);
return false;
}
return true;
}
public synchronized boolean sottrai(int decremento){
String threadName = Thread.currentThread().getName();
n-=decremento;
System.out.println(threadName + " valore di n = "+n);
if(n<80){
System.out.println("Fine del thread " + threadName);
return false;
}
return true;
}
}
class Thread_I implements Runnable {
Shared n;
public void Thread_I (Shared n) {this.n=n;}
public void run() {
int i = 0;
while(i<1000){
try{
Thread.sleep(100);
}catch (InterruptedException e) {}
int inc = (int)(Math.random()*10);
if (! n.somma(inc)) return;
i++;
}
}
}
class Thread_D implements Runnable {
Shared n;
public void Thread_D (Shared n) {this.n=n;}
public void run () {
int i = 0;
while(i<1000){
try{
Thread.sleep(300);
}catch (InterruptedException e) {}
int decr = (int) (Math.random()*10);
if(!n.sottrai(decr)) return;
i++;
}
}
}