I have this simple code in Java 8:
class ThreadTest {
void threadTest() {
new Thread(this::threadTest).start();
System.out.println(Thread.activeCount());
}
public static void main(String[] args) {
new ThreadTest().threadTest();
}
}
and I was pretty much expecting to see very large numbers getting printed. All I see in the console is:
4
4
4
4
4
4
4
4
4
I said maybe I am not able to see others for whatever reason and modified the code as below:
class ThreadTest {
void threadTest() {
new Thread(this::threadTest).start();
if (Thread.activeCount() > 4) {
System.out.println(Thread.activeCount());
}
}
public static void main(String[] args) {
new ThreadTest().threadTest();
}
}
and now nothing gets printed.
What am I missing here?
You need to prevent too many threads from being spawned, a problem that could potentially result in a denial of service owing to exhausted system resources.
Each CPU core can have up to two threads if your CPU has multi/hyper-threading enabled. You can search for your own CPU processor to find out more.
Only 1 native CPU thread can be executed at a time by 1 single core. If for example you have 4 cores, only 4 threads can be executed at the same time (if you have 2 thread/core still one will execute at a time, next will wait to be executed as soon as first finish).
The truth is, you can run as many threads in Python as you have memory for, but all threads in a Python process run on a single machine core, so technically only one thread is actually executing at once. What this means is that Python threads are really only useful for concurrent I/O operations.
Once your thread reaches the end of its execution (in your case, the end of the threadTest()
method), it is no longer an active thread.
If you add an excessively long Thread.sleep
in your method, you will see this active thread count increase further.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With