It seems that the best solution here is to place a synchronized block around the while statement

Java Code:
synchronized(MyAnswer.class){
while (n<100) {
System.out.print(str);
System.out.println();
n++;
}
}
It doesn't have to be MyAnswer.class object, you can create any class level object as long it's not "synchronized(this)" or any private member of the thread instance