Java - relationship between threads and CPUs

后端 未结 3 1380
遇见更好的自我
遇见更好的自我 2021-02-08 07:41

I am pretty new to multithreading, and I am working on a project where I am trying to utilize 4 CPUs in my Java program. I wanted to do something like

int numP         


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-02-08 07:57

    "if it sees there is more availability on another CPU, will it kill the thread and spawn a new one there?"

    There is no need to kill and spawn another one to employ available CPU. Threads are memory objects that are not bound to particular CPU, and can float around from one CPU to another. Thread execution is a loop like this:

    • Thread.start() puts the thread into the processor queue
    • when there is available processor, scheduler takes the first thread in the processor queue an puts on the processor
    • when the thread blocks on an occupied lock, or is waiting for the end of an I/O operation, it is taken off the processor and is put in the corresponding queue. When the lock is freed, or I/O operation finishes, the thread is moved from that queue back to the processor queue.
    • when the thread works too long without blocking (o/s dependant time, say, 50 ms), an interrupt happens, and the scheduler looks if there are threads in the processor queue. If there are, current thread is taken off the processor and put at the end of the processor queue, and the first thread in the queue it put on the processor. This way the long running thread lets other threads to execute too.

    As a result, threads often change their state but this is transparent to programmer. The whole idea of threads is that thread is a model of a processor, more convenient than real processor. Use that model and don't worry about mapping threads on processors, until you really need to.

提交回复
热议问题