Reputation: 19980
So the STB is dual core. I thought we can only create 2 proper threads.
In every keyreleased()
I am creating a new thread
Runnable runnable = new Runnable()
{
int i = j;
public void run()
{
while (true)
{
System.out.println("This thread is running always number is " + i);
}
}
};
Thread th = new Thread(runnable);
th.setPriority(Thread.MAX_PRIORITY);
th.start();
j++;
//...
}
But even after creating 20 more threads, box doesn't have any issues.
Is it because JVM realized that the run block is empty and it optimized the code ? Or is the JVM implementation for while(true) is different ?
Note: i have tried putting Thread.sleep(1000) as well but no problems
Upvotes: 3
Views: 3114
Reputation: 62439
Short answer: you can keep creating user threads until your JVM/OS can't handle any more.
Long answer: to quote from another answer I gave to this question:
The term threads usually covers three abstraction layers:
What you are creating in your application are User threads. As you can see, many user threads can map to a smaller number of hardware threads (the actual number of concurrent threads the hardware can handle, in this case 2).
The multiple layers that exist between the user threads and the lower levels apply their own scheduling mechanisms to move threads on and off the hardware cores, in order to enforce fairness, load-balancing or priority.
Upvotes: 2
Reputation: 36339
The number of possible threads has nothing to do with CPU cores. It is rather a function of available memory. Every thread needs a separate stack, so depending on stack size, the number is limited.
For example, try:
java -Xss8m -Xmx64m .....
You'll probably notice that you can't create that many Threads.
Upvotes: 3
Reputation: 875
Threads are not tied to physical or logical processor cores. The operating system manages threads in a part called scheduler. Basically every thread gets a certain amount of time to run on a processor core then it gets paused and the next thread has time to run, after some time the first thread has again time to run.
Upvotes: 1
Reputation: 39457
You can run 20 threads even on a single-core machine. What happens is called time slicing.
http://en.wikipedia.org/wiki/Time_slice#Time_slice
It is a way for the processor to simulate multiple processors executing multiple tasks as once.
Upvotes: 6