I'm trying to create two threads, one thread display even integers from 0 to 10, one thread display odd integers from 1 to 11. Is the following code suitable for designing this program?
public class Mythread {
public static void main(String[] args) {
Runnable r = new Runnable1();
Thread t = new Thread(r);
t.start();
Runnable r2 = new Runnable2();
Thread t2 = new Thread(r2);
t2.start();
}
}
class Runnable2 implements Runnable{
public void run(){
for(int i=0;i<11;i++){
if(i%2 == 1)
System.out.println(i);
}
}
}
class Runnable1 implements Runnable{
public void run(){
for(int i=0;i<11;i++){
if(i%2 == 0)
System.out.println(i);
}
}
}
package p.Threads;
I would just change a few details (no need to use the modulo operator here...):
I would also look at using Java Concurrency if you want alternatives. Some of the functionality provided in the Java Concurrency package offer a higher level of abstraction then using the Thread class directly and provide more functionality as a result.
For your specific case what your doing is quite reasonable however is the order of the printing of these numbers important? Do you want evens before odds? These kinds of questions would better indicate the design that most suits your needs.
OUTPUT :-
odds 1 odds 3 odds 5 odds 7 odds 9 evens 2 evens 4 evens 6 evens 8
Yes it is fine. But in this case, I don't think you need 2 threads are all, because the operation is simple. However, if you are practicing threads, it is OK