|
Hi all,
This may sound trival but does anyone has examples on declaring an array of Threads?
Thanks
|
|
|
There you go:
import java.lang.*;
public class thready implements Runnable {
public void run(){
Thread[] mythreay = new Thread[20];
}
}
|
|
|
Thanks for your help mmarab,
Does your solution also applies to this :-
MyConstructor newObj = new MyConstructor( "name" , age);
.
.
.
Thread newObj = new Thread[5];
.
.
.
newObj[0].start();
newObj[1].start();
.
.
Is this legal? Anyone can verify this can work?
Thanks
|
|
|
Yes that should work fine!
|
|
|
Hi ,
When I try to complie, it prompt the error
" cannot find symbol. class MyConstructor. netObj[x].start()". Do you all think my start() statement should be in the class MyConstructor although there is no main(String[] args) method?
Thanks
Eric
|
|
|
Ok this is your code :
[start]
MyConstructor newObj = new MyConstructor( "name" , age);
.
.
.
Thread newObj = new Thread[5];
.
.
.
newObj[0].start();
newObj[1].start();
[end]
From this i guess you have a class called MyConstructor, you create an object from it called newObj, but then you try and make a thread from that class by using the same variable newObj as a thread. This is incorrect. Try this:
import java.lang.*;
public class TestThread extends Thread{
public TestThread() {
}
public static void main(String[] args){
TestThread[] myThread = new TestThread[10];
myThread[0].start();
myThread[1].start();
}
}
this class extends thread, which means it has thread attributes, it can be treated like a thread, using thread methods. So i create an array called myThread, which is of type TestThread(my class) and can then use the method start(), as the class extends thread.
Hope this helps.
|
|
|
Thank you mmarab,
That solves the error message. I tried to implement Runnable and it works too.
|
|
|
Excellent, glad that it helped!
|
|
|