I am just testing out some threads, trying to figure out how to use them. My question is, how can I get my current scenario to work how I want it?
I want to have this program print out 1 - 100. I have two methods; oddNumbers
and evenNumbers
oddNumbers:
public static void oddNumbers() {
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 1) {
System.out.println(i);
}
}
}
}).start();
}
evenNumbers:
public static void evenNumbers() {
new Thread(new Runnable() {
public void run() {
for (int q = 0; q < 100; q++) {
if (q % 2 == 0) {
System.out.println(q);
}
}
}
}).start();
}
main method
public static void main(String[] args) {
evenNumbers();
oddNumbers();
}
So, from what I understand, the methods oddNumbers
and evenNumbers
are running on different threads. So if they are, then why isn't my output 1-100?
Here's the output I get:
0
2
4
6
.
.
.
50
1
3
5
.
.
.
99
52
54
56
.
.
.
100
About half way through the evenNumbers
loop, the oddNumbers
loop cuts it off. Why does this happen, and how do I set it up so that it'll print 1-100?
Thanks in advance!