Heavy weight and light weight thread

后端 未结 3 1799
臣服心动
臣服心动 2020-12-25 14:29

What are the Light weight and heavy weight threads in terms of Java?

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-25 14:52

    It's related to the amount of "context" associated with a thread, and consequently the amount of time it takes to perform a "context switch".

    Heavyweight threads, (usually kernel/os level threads) have a lot of context (hardware registers, kernel stacks, etc). So it takes a lot of time to switch between threads. Heavyweight threads may also have restrictions on them, for example, on some OSes, kernel threads cannot be pre-empted, which means they can't forcibly be switched out until they give up control.

    Lightweight threads on the other hand (usually, user space threads) have much less context. (They essentially share the same hardware context), they only need to store the context of the user stack, hence the time taking to switch lightweight threads is much shorter.

    On most OSes, any threads you create as a programmer in user space will be lightweight in comparison to the kernel space threads. There is no formal definition of heavyweight and lightweight, it's just more of a comparison between threads with more context and threads with less context. Don't forget that every OS has its own different implementation of threads, and the lines between heavy and light threads are not necessarily clearly defined. In some programming languages and frameworks, when you create a "Thread" you might not even be getting a full thread, you might just be getting some abstraction that hides the real number of threads underneath.

    [Some OSes allow threads to share address space, so threads that would usually be quite heavy, are slightly lighter]

提交回复
热议问题