0
I’m seeing threads now and doing some experiments. It’s a simple test, I want to print on the console ten times the name of each thread by inserting into the same object of type List
in a synchronized way (one ends the other begins).
The problem is that my program keeps giving Exception ArrayIndexOutOfBoundsException
with a very fickle output. One hour prints the threads names correctly, and in the end Exception, another neither prints the names on the screen.
Follows the code:
import java.util.List;
public class ThreadsTeste {
public static void main(String[] args) {
TarefaAdicionaString obj = new TarefaAdicionaString();
List<String> lista = obj.getLista();
Thread thread1 = new Thread(obj, "Thread - 1");
Thread thread2 = new Thread(obj, "Thread - 2");
thread1.start();
thread2.start();
for(int i=0; i < 100; i++){
System.out.println(lista.get(i));
}
}
}
import java.util.List;
import java.util.Vector;
public class TarefaAdicionaString implements Runnable{
public List<String> lista = new Vector<String>();
public List<String> getLista(){
return this.lista;
}
@Override
public void run() {
synchronized(this){
for(int i=0; i < 10; i ++){
this.lista.add(Thread.currentThread().getName());
}
}
}
}
And what would be a safer option for execption not to appear?
– Lucas Marinzeck
@Lucasmarinzeck The code you gave is a very "artifical" problem, so it’s hard to say what the best approach would be to be naturally explored in your real problem. However, it is most likely that the best solution is to exchange the
for (int i=0; i < 100; i++) { System.out.println(lista.get(i)); }
forfor (int i=0; i < lista.size(); i++) { System.out.println(lista.get(i)); }
or better still, byfor (String x : lista) { System.out.println(x); }
.– Victor Stafusa