I create new Thread and start it. It’s run method has following code:
for (int a=0; a<10; a++) {
System.out.println(a);
Thread.sleep(10);
}
And what I get is:
0
0
1
1
2
0
2
3
1
0
3
4
2
1
0
4
5
3
2
1
0
5
6
4
… and so on. Why I don’t get 1 2 3 4 5 6 7 8 9 ? What’s the reason?
EDIT:
Thread code:
private class WarpEnemyRnn implements Runnable {
private WarpEnemy enemy;
public WarpEnemyRnn(WarpEnemy enemy) {
this.enemy = enemy;
}
@Override
public void run() {
try {
for (int a=0; a<8; a++) {
System.out.println(a);
enemy.subOpacity();
Thread.sleep(refreshRate);
}
Point2D warpPoint = enemy.warp();
enemy.setX((int) warpPoint.getX());
enemy.setY((int) warpPoint.getY());
enemy.resetWarpCooldown();
for (int a=0; a<8; a++) {
enemy.addOpacity();
Thread.sleep(refreshRate);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
New thread is created in other thread which runs every 15ms. It’s created only when some condition agrees.
All threads print to the same standard output.
Every time you see a 0 printed out is when a new thread is created.
Here are your threads:
Each is printing the numbers in sequence.
Note – It’s not guaranteed for each output to be assigned to the thread I specified, this is just one possible alignment of outputs (e.g. the output of the the first two threads are interchangeable), but the timing suggests that this is indeed the correct assignment.
You could add a unique ID to each thread if you want to see which thread prints what.