How to pass parameters to a Thread in Java

If you are creating a thread you would often need to pass some information to that thread to work on. So how do you do that with Java threads. The simplest way is to pass this information as parameter to the Thread.

Here is a simple example to do the same.


Java Code to pass parameters to a Thread


public class ThreadSample{
public static void main(String [] args){
new FindSum(1,2,100).start();
}
}
class FindSum extends Thread{
int arg1, arg2, argn;
FindSum(int arg1, int arg2, int argn){
this.arg1 = arg1;
this.arg2 = arg2;
this.argn = argn;
}
public void run() {
int sum = arg1 + arg2 + argn;
System.out.println("The sum of numbers is: " + sum);
}
}

Keep coding. Keep delegating !!!

Leave a Reply

Your email address will not be published. Required fields are marked *