passing objects into threads
Hi all...
I know I am going to get flamed for this, because its so simple and its most likley been asked so many times before (I did several searches.. but no go)... but:
How do I pass an object (ie an array) into a Thread.. take this example:
publicclass HelloThreadextends Thread{
publicvoid run(){
System.out.println("Hello from a thread!");
}
publicstaticvoid main(String args[]){
(new HelloThread()).start();
}
}
how would I get "args[]" into the "HelloThread" ?
so I would be able to do this:
publicclass HelloThreadextends Thread{
publicvoid run(){
System.out.println("Hello from a thread!");
int i = args.length;//see here!!!! I need to be able to referance args[] from main()
}
publicstaticvoid main(String args[]){
(new HelloThread()).start();
}
Thanks for any help.. I love java, and have been using it for all my projects!
You pass arguments into threads with the constructor.
public class HelloThread extends Thread {
private int i = 0;
public HelloThread(String[] args) {
i = args.length;
}
public void run() {
System.out.println("Hello from a thread: " + i + "!");
}
public static void main(String args[]) {
HelloThread myThread = new HelloThread(args);
myThread.start();
}
}
kev@mymachine ~/java$ java HelloThread
Hello from a thread: 0!
kev@mymachine ~/java$ java HelloThread 2
Hello from a thread: 1!
kev@mymachine ~/java$ java HelloThread 1 2 3
Hello from a thread: 3!
public class R implements Runnable {
private String[] strings;
public R (String[] strings) {
this.strings = strings;
}
public void run() {
for(String s : strings) {
System.out.println(s);
}
}
public static void main(String[] args) {
if (args.length == 0)
args = new String[] {"hello", "world"};
Runnable r = new R(args);
Thread t = new Thread(r);
t.start();
}
}
Notice this has nothing to do with threads, per se.
You could just a well ask: how can I pass an array to an instance of class R so
that it can access the array later?
> awesome... thanks guys.. I had an idea that it would
> have to be done with the constructor, but was not
> quite sure how to achieve it..
Just to note. It doesn't have to be with the constructor. It could be with a method or property of the class as well.
However once the thread has been started there are some concurrency issues to consider.