3

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

Jeril Kuruvila
  • 17,190
  • 1
  • 20
  • 23

4 Answers4

6

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.

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
  • what about the while(true) ? Isn't the while(true) supposed to completely block the thread. – Jeril Kuruvila Dec 03 '13 at 11:02
  • The while(true) is almost irrelevant; you are calling sleep(). Try removing the call to sleep, then you'll see the true impact of an uninterrupted infinite loop. – Charles Goodwin Dec 03 '13 at 11:04
  • My First try was obviously without sleep. My understanding is that sleep will hold the thread Java doc says sleep Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors. – Jeril Kuruvila Dec 03 '13 at 11:07
  • Calling sleep is a different thing: your currently executing Thread is saying to the processor: "now I will sleep, maybe go find and execute some other Thread, or do what you have to do, as I will now just sleep for a while; and btw don't come back to me for at least N milliseconds". This is how you can think about it. – peter.petrov Dec 03 '13 at 11:13
  • Your code of Thread1 gets preempted and the processor switches to the other thread of execution - say Thread2. This can happen even when your current thread Thread1 is busy. The processor just saves its state and lets another thread like Thread2 execute. Then it switches to Thread3, Thread4 and so on. At some point it switches back to Thread1 and lets it continue from where it was. This is my understanding of things. – peter.petrov Dec 03 '13 at 11:19
  • Then what about wait(millis), why we need wait(millis) then. By the way coming back to my question , if like peter.petrov said, the state is saved , then if i create 100 threads then processor has to maintain 99 thread state objects, eventually will it be too much for processor to handle. Please don't shout at me, if this is a stupid question. Sorry. – Jeril Kuruvila Dec 03 '13 at 11:20
  • No, this observation is correct. You cannot run endless count of threads and rely that time-slicing will always solve things for you. Now, the wait, notify, notifyAll are 3 very important methods. But they are related to object monitors and provide a way of "sending signals" between threads. You will need to read and think about them, they are a totally different subject. Compared to them sleep is just a simple sleep indeed. See this for example: http://www.javaworld.com/javaworld/jw-07-2002/jw-0703-java101.html – peter.petrov Dec 03 '13 at 11:28
  • wait(long timeout) Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. Let us assume that nobody called notify or notifyAll then what is the difference between sleep and wait. I got your point and i know that wait() and notify/notifyAll is for communication between threads. – Jeril Kuruvila Dec 03 '13 at 11:30
  • Method sleep is a static method of Thread. Method wait is a method on an Object. Simply put: when you call wait on an Object your currently executing thread suspends until some other Thread calls notify or notifyAll on that same object. Need to go offline now. See the link above, I changed it to something better. It is quite old but would give you the basics. Also, make a test, call e.g. obj.wait(50) from ThreadA, don't call obj.notify() on the same object from ThreadB, see what happens (if your ThreadA is re-enabled or not). – peter.petrov Dec 03 '13 at 11:38
  • 1
    @JerilKuruvila hundreds of thread-state objects is not a problem. They are not huge and 'handling' them is mostly moving around a pointer to them on queues and other containers. Try it - create 500 sleepy threads and you will find it has no noticeable impact on the performance of your machine. – Martin James Dec 03 '13 at 12:00
  • @peter.petrov I am calling object.wait(millis) and it is working fine. Runnable a = new Runnable() { public void run() { System.out.println("before wait"); synchronized (obj) { try { obj.wait(100); } catch (InterruptedException ex) { } } System.out.println("After waiting "); } }; new Thread(a).start(); } } – Jeril Kuruvila Dec 04 '13 at 06:13
3

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.

Ingo
  • 36,037
  • 5
  • 53
  • 100
2

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:

  • User threads are threads launched by applications and are mapped N:M to:
  • Kernel threads, which are threads managed by the operating system, mapped N:M to:
  • Hardware threads, which are the actual physical resources available.

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.

Community
  • 1
  • 1
Tudor
  • 61,523
  • 12
  • 102
  • 142
  • Hi Tudor, What happens if i put all that code in a while(true) loop. According to your explanation it won't make any difference right ? – Jeril Kuruvila Dec 03 '13 at 11:48
  • @Jeril Kuruvila: It won't make a difference as long you have enough RAM available to spawn threads and the scheduler doesn't choke on too many threads. 20 threads should not be a problem. – Tudor Dec 03 '13 at 11:53
  • So there is a problem with your answer then. Box is running and it is creating threads, but it is not responding to keys. Earlier without top level while(true) , it was working fine. Can you explain this behavior ? Note: Now thousands of threads are getting created. My this comment is not to fight against your valuable answer. – Jeril Kuruvila Dec 03 '13 at 12:01
  • 1
    @Jeril Kuruvila: Thousands of threads are likely to cause an impact since each thread needs to be scheduled and it takes up a certain amount of stack space. The scheduler is so busy with managing threads that your system becomes unresponsive. This is expected behavior. – Tudor Dec 03 '13 at 12:06
  • It look a while to understand ,but thanks for bearing with me @Tudor,@peter.petrov. – Jeril Kuruvila Dec 03 '13 at 12:17
  • @Tudor 'Thousands of READY/RUNNING threads are likely to cause an impact'. Also, the scheduler will be hardly any busier with 5000 ready threads than with 16, (assuming 8 cores or less). The impact arises because the non-scheduler, user time is then spread out over 5000 threads. – Martin James Dec 03 '13 at 13:28
1

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.

Jan Henke
  • 875
  • 1
  • 15
  • 28