I the program I wish to run is a search for a number in 4 threads. Its working out fine and here is the code.
import java.lang.Math;
import java.lang.Thread;
public class NumberFinder
{
public static void main(String args[])
{
int target = (int) (Math.random()*1000);
System.out.println("The number is " + target);
Thread thread0 = new Finder(target, 0, 249);
Thread thread1 = new Finder(target, 250, 499);
Thread thread2 = new Finder(target, 500, 749);
Thread thread3 = new Finder(target, 750, 1000);
thread0.start();
thread1.start();
thread2.start();
thread3.start();
}
}
class Finder extends Thread
{
int searchFor;
int beginRange;
int endRange;
public Finder(int searchFor, int beginRange, int endRange)
{
this.searchFor = searchFor;
this.beginRange = beginRange;
this.endRange = endRange;
System.out.println ("in constructor " + this.getName() + " " + beginRange + " " + endRange);
}
public void run()
{
for (int i = beginRange; i < endRange; i++){
if (searchFor == i){
System.out.println("found at " +this.getName()+ " and the number is "+ i);
}
}
}
}
Now I wish to use Runnable instead of extends Thread
import java.lang.Math;
import java.lang.Thread;
public class NumberFinder
{
public static void main(String args[])
{
int target = (int) (Math.random()*1000);
System.out.println("The number is " + target);
Thread thread0 = new Finder(target, 0, 249);
Thread thread1 = new Finder(target, 250, 499);
Thread thread2 = new Finder(target, 500, 749);
Thread thread3 = new Finder(target, 750, 1000);
thread0.start();
thread1.start();
thread2.start();
thread3.start();
}
}
class Finder implements Runnable
{
Thread t = Thread.currentThread();
int searchFor;
int beginRange;
int endRange;
public Finder(int searchFor, int beginRange, int endRange)
{
t.searchFor = searchFor;
t.beginRange = beginRange;
t.endRange = endRange;
System.out.println ("in constructor " + t.getName() + " " + beginRange + " " + endRange);
}
public void run()
{
for (int i = beginRange; i < endRange; i++){
if (searchFor == i){
System.out.println("found at " +this.getName()+ " and the number is "+ i);
}
}
}
}
But this code is not compiling. How to correct the code?