结果:
dodopipe@T-PC-U:~/workspace/Test/src$ java languagelearning.multithread.MultithreadTest
I am thread 1 : Hi
main thread
I am thread 2 : Hello!
I am thread 1 : Hi
main thread
I am thread 2 : Hello!
I am thread 1 : Hi
main thread
I am thread 2 : Hello!
I am thread 1 : Hi
main thread
I am thread 2 : Hello!
I am thread 1 : Hi
...
public MultithreadTest1(int number) {
this.number = number;
}
public static void main(String[] args) throws InterruptedException {
//create thread
int i = 1;
while (i <= 5) {
(new MultithreadTest1(i)).start();
i++;
}
//hold main thread
while(true) {
System.out.println("I am main thread");
Thread.sleep(1000);
}
}
}
结果:
I am thread No. 2
I am main thread
I am thread No. 5
I am thread No. 3
I am thread No. 4
I am thread No. 1
I am thread No. 2
I am thread No. 5
I am thread No. 3
I am main thread
I am thread No. 4
I am thread No. 1
I am thread No. 2
I am thread No. 5
I am main thread
I am thread No. 4
I am thread No. 3
I am thread No. 1
...