When I run this code, the output is "something is added" and then infinite loop ...
My program should print:
something is added
something is printed
I don't understand why the program can not exit while loop
import java.util.LinkedList;
public class Test {
static LinkedList<String> list = new LinkedList<String>();
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
while(list.isEmpty()); // here is the loop
System.out.println("something is printed"+list.get(0));
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try{
Thread.sleep(200);
list.add("something");
System.out.println("something is added");
}catch (Exception e) {}
}
}).start();
}
}
I am looking for solution and explanation
Thanks A lot
In order for threads to communicate and share data safely, they have to be properly synchronized. The simplest way to do that in your example is to wrap your list in a synchronized wrapper:
static List<String> list = Collections.synchronizedList(new LinkedList<>());