I want to create two threads.One thread will have to print odd numbers and the other thread will have to print even numbers between 1-20 numbers. This is the code I have attempted so far but it doesn't give the expected output.
public class JavaApplication40 extends Thread {
@Override
public void run(){
while (true){
for (int i=0;i<=20;i++){
if(i%2!=0){
System.out.println("odd " +i);
}
}
}
}
public static void main(String[] args) {
Thread t =new JavaApplication40();
for (int x=0;x<=20;x++){
if(x%2==0){
System.out.println("even " + x);
}
}
}
}
This code only outputs even numbers.I want odd numbers too.Someone please tell me how I can modify the above code to get the expected output.
After you create a Thread you need to call start() it to start it. Try calling
t.start();
Additionally, You should extend Thread. Instead you should implement Runnable and wrap it with a Thread. Also you don't need to check if a value is odd or even if you make sure the value is always odd or even.
public class JavaApplication40 {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
public void run() {
// starting at 1 and counting by 2 is always odd
for (int i = 1; i < 10000; i += 2)
System.out.println("odd " + i);
}
});
t.start();
// starting at 0 and counting by 2 is always even
for (int x = 0; x < 10000; x+=2)
System.out.println("even " + x);
}
}
Note: the whole point of using Threads is to have independent execution and Threads take time to start. This means you could get all the even and all the odd number together. i.e. it prints them faster than a thread starts.
You might need to print much more numbers to see them printed at the same time. e.g. 10_000 instead of 20.
You created your thread, but never started it.
Thread t =new JavaApplication40();
creates it, when started, it will call run()
Start it with t.start()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With