Reputation: 30284
I have read a client-server application and clients interact together through server. So, for this purpose, I want to create client on different thread. (if not, they often block by IO).
Here is my client code :
public class Client {
//some client code here
public static void main(String[] args) {
new Thread() {
@Override
public void run() {
long threadId = Thread.currentThread().getId();
System.out.println("Client creator thread id: " + threadId);
Client c = new Client();
// some code to run client
}
}.start();
}
}
I run this class file multiply times (by running directly in IDE, or create bat file) . And I notice that all of them are on same thread (same thread id). I cannot explain why.
I think the problem I meet is : I don't create multiply threads in same class, but run this class multiply times. Although I think this makes strange problem, but still cannot explain why.
Please explain for me and how to correct this.
Thanks :)
Upvotes: 2
Views: 162
Reputation: 1218
If you really want to test / emulate multiple clients, than you should start multiple processes. So you also wouldn't have to mess around with creating threads. In reality, the clients will never run in the same process (even not on the same machine?). That won't make you understand this thing, but I would get you nearer to the reality.
Upvotes: 0
Reputation: 13529
If you spawn the thread in a for loop like this :
public class Client {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread() {
@Override
public void run() {
long threadId = Thread.currentThread().getId();
System.out.println("Client creator thread id: " + threadId);
Client c = new Client();
// some code to run client
}
}.start();
}
}
}
you will find many threads in one process with different IDs. If you just keep running the main(), you are just creating another process with only one thread in it.
Upvotes: 1
Reputation: 49402
Probably because you are running a single thread each time, and after it ends you run the main()
method again, which creates another thread with the same id. The similarity in id is expected as per the documentation in getID()
method, which says "When a thread is terminated, this thread ID may be reused." Read here for more.
Upvotes: 1