Reputation: 15
I've been working on threads in Java, and this is my attempt at doing running 2 different threads to output the even numbers from 1-30, as well as the odd numbers from 1-30, each in a different thread. I am not sure if I've done something wrong or not, and I hope you can lend me some help.
public class evenThread implements Runnable{
public static void run(){
System.out.println("Even Numbers: ")
for(int j = 2; j <= 30; j + 2){
System.out.println(", " & j);
}
}
}
public class oddThread implements Runnable{
public static void run(){
System.out.println("Odd Numbers: ")
for(int i = 1; i <= 30; i + 2){
System.out.print(", " & i);
}
}
}
public static void main(String args[]){
evenThread t1 = new evenThread();
oddThread t2 = new oddThread();
t1.start();
t2.start();
}
}
Upvotes: 0
Views: 73
Reputation:
here are runnables you need to use:
Thread whatever=new Thread(new evenThread());
Thread whatever2=new Thread(new oddThread());
or use extends Thread instead of implements runnable
there is no start method on a runnable you can know this because implements doesn't ever add code it just informs other things that you will have a method in YOUR CODE so they can call that method.
Upvotes: 2
Reputation: 12668
I don't know how you are compiling it because run methods should not be static because you are suppose to call instance methods secondly oddThread
and evenThread
classes should be in separate java file or should be inner classes of Main (which currently you don't even have) and for inner class referred from main should be mark as static as well. I have fixed your code as following you can check the difference e.g. + sign used to concatenate strings
public class Main {
public static void main(String args[]) {
Thread t1 = new Thread(new evenThread());
Thread t2 = new Thread(new oddThread());
t1.start();
t2.start();
}
public static class evenThread implements Runnable {
public void run(){
System.out.println("Even Numbers: ");
for(int j = 2; j <= 30; j = j + 2){
System.out.print(", " + j);
}
}
}
public static class oddThread implements Runnable {
public void run(){
System.out.println("Odd Numbers: ");
for(int i = 1; i <= 30; i = i + 2){
System.out.print(", " + i);
}
}
}
}
Upvotes: 1
Reputation: 3174
evenThread and oddThread implement Runnable.
To get startable Threads you have to wrap them in Threads
Runnable even = new evenThread();
Thread t1 = new Thread(even);
t1.start();
It is not possible to start Runnables alone in Java.
Oh, and of corse, the run-Method must not be static.
Upvotes: 0