Howto add thread to ThreadGroup
Hello,
If i create a thread what is it add threadGroup.
example:
public class OneThread extends Thread {
public boolean state = true;
public OneThread() {
}
public void run() {
while( state != false ) {
System.out.println("Running");
wait(2000);
}
}
public void ThreadStop() {
state = false;
}
}
OneThread one = OneThread();
one.start;
if I create one or more thread howto add the ThreadGroup?
Regards
Richard
you have to define the threagroup when creating the threadsee http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#Thread(java.lang.ThreadGroup,%20java.lang.String)
Hello,OK, this is I know, but if i as follow create the Thread then howto add threadGroup. as i write up.Richard
>OneThread one = OneThread()
? Use the new operator.
For ThreadGroup, you create the group first, then you add threads to the group, not the reverse, since you mat have noticed that ThreadGroup doesn't have an add method.
ThreadGroup tgroup = new ThreadGroup(unique_name);
//add threads to tgroup
Thread t = new Thread(tgroup, thread_name);
sorry yes, to be out of new operator. If i create Thread so write up then I don't add thread to ThreadGroup? I think! This is correct?RegardsRichard
i just didn't understand the last reply, richard ; if you're french, i can speak to you in french if you prefer
Sorry, I don't speak good english. I'm Hungarian. My problem: If i Create new Object whit the extends Thread class (but i think this is a Thread) , then I don't add ThreadGroup this? I hope so clear, you know my own mind.Richard
you must know that:
- there is no necessity for putting a thread in a group
- if you WANT or NEED to put it in a group, the procedure is the following one:
1 : create a threadgroup object
2 : when you create your thread (or thread extension) object, you have to call the constructor containing the threadgroup parameter
a reply was posted to show you how to proceed ; take a look at it
but keep in mind that there it's not an obligation to handle thread groups
example:
public class OneThread extends Thread {
public boolean state = true;
public OneThread() {
}
public void run() {
while( state != false ) {
System.out.println("Running");
wait(2000);
}
}
public void ThreadStop() {
state = false;
}
}
ThreadGroup thg = new ThreadGroup("etc");
OneThread one = OneThread(thg);
one.start;
This is correct? if I see you write for me.
Richard
that's no good, here is what you should do:
define a constructor:
public OneThread(ThreadGroup tg, String threadName) {
super(tg, threadName);
}
in your OneThread class
then, what you do is:
ThreadGroup myGrp = new ThreadGroup("mygroup");
OneThread t = new OneThread(myGrp, "mythread");
and you're done
wow, this is super. Thanks for your help me!Best RegardsRichard