I am trying to write a short Java program that uses multiple threads. I want the main-thread to print "i," every 100ms. And the sub-thread prints "Test" every 1000ms.
The result should be like this.
0,1,2,3,4,5,6,7,8,9,Test
10,11,12,13,14,15,16,17,18,19,Test
20,21,22,23,24,25,26,27,28,29,Test
30,31,32,33,34,35,36,37,38,39,Test
40,41,42,43,44,45,46,47,48,49,Test
50,51,52,53,54,55,56,57,58,59,Test
60,61,62,63,64,65,66,67,68,69,Test
70,71,72,73,74,75,76,77,78,79,Test
80,81,82,83,84,85,86,87,88,89,Test
90,91,92,93,94,95,96,97,98,99,Test
But my result is this.
0,1,2,3,4,5,6,7,8,9,Test
10,11,12,13,14,15,16,17,18,Test
19,20,21,22,23,24,25,26,27,Test
28,29,30,31,32,33,34,35,36,Test
37,38,39,40,41,42,43,44,45,Test
46,47,48,49,50,51,52,53,54,Test
55,56,57,58,59,60,61,62,63,Test
64,65,66,67,68,69,70,71,72,Test
73,74,75,76,77,78,79,80,81,Test
82,83,84,85,86,87,88,89,90,91,Test
92,93,94,95,96,97,98,99,
Here is my full code:
public class Main {
public static void main(String[] args){
Main.repeatTask(10, 1000);
//print i, then sleep 100ms
for(int i=0;i<100;i++){
System.out.print(i + ",");
try{
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();
}
}
}
//sleep (time)ms then print "Test"
public static void repeatTask(int m, int time) {
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < m; i++) {
try {
Thread.sleep(time);
System.out.println("Test");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
And I can`t change the main method. How can I change my method repeatTask?