Code:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
public class NameOutput extends Thread{
private List<String> list = new ArrayList<>();
private String name;
public NameOutput(String name) {
this.name = name;
synchronized (list) {
list.add(this.name);
}
}
@Override
public void run() {
while(true) {
for(int i = 0; i < list.size(); i++) {
synchronized(list) {
try {
Thread.sleep(1000);
System.out.println(getName() + ": " + list.get(i));
} catch (InterruptedException e) {
}
}
}
}
}
public static void main(String[] args) {
Thread thread = new NameOutput("Beka");
Thread thread1 = new NameOutput("Anna");
Thread thread2 = new NameOutput("Gela");
thread.start();
thread1.start();
thread2.start();
try {
thread.join();
thread1.join();
thread2.join();
}catch(InterruptedException e) {
}
}
}
Thread-0
Thread-1
Thread-2
Thread-0
Thread-1
Thread-2
Thread-0
Thread-1
ausgegeben wird.