Can someone please explain or give an example on how to create multiple threads with different functionalities in Java?
This is the code... I am trying to create a thread that does what public void rnd_list() is supposed to do ( a list of 30 random numbers) which is a different task than the one define in public void run() which is the method that by default when thread.start() its executed. I want to know how to create a thread within the same class Apple with a different functionality in this case the one in public void rnd_list().
import java.util.Random;
public class Apple implements Runnable{
String name;
int time, number, first, last, maximum;
Random r = new Random();
Random n = new Random();
int[] array = new int[10];
public Apple(String s, int f, int l){
name = s;
first = f;
last = l;
maximum = array[0];
}
// public void rnd_list()
// {
// for(int j = 0; j < 30; j++)
// {
// number = n.nextInt(100);
// array[j] = number;
// System.out.println("thread" + name + "array [" + j + "] =" + array[j]);
// }
// }
public void run(){
try{
for(int i = first; i < last; i++ )
{
if(maximum < array[i])
{
maximum = array[i];
}
}
System.out.println("maximum = " + maximum);
}catch(Exception e){}
}
public static void main(String[] args){
Thread t1 = new Thread(new Apple("one ", 0, 2));
Thread t2 = new Thread(new Apple("two ", 3, 5 ));
Thread t3 = new Thread(new Apple("three ", 6, 9));
try{
t1.start();
t2.start();
t3.start();
}catch(Exception e){}
}
}