📜  Java线程和 OS 线程之间的区别

📅  最后修改于: 2022-05-13 01:55:27.449000             🧑  作者: Mango

Java线程和 OS 线程之间的区别

多线程是一种Java特性,它允许同时执行程序的两个或多个部分,以最大限度地利用 CPU。这种程序的每一部分都称为一个线程。因此,线程是进程中的轻量级进程。

主要区别在于同一进程内的线程运行在共享内存空间中,而进程运行在不同的内存空间中。线程是进程内的执行路径。一个进程可以包含多个线程。现在让我们讨论Java线程和OS线程之间的区别。首先,我们将在一个程序的帮助下定义它们,以便我们能够更好地理解,最后我们将以表格方式列出它们之间的差异。

Java线程与 OS 线程



Key Point OS ThreadsJava Threads
DefinitionA thread is the smallest unit of processing that can be performed in an OSA thread, in the context of Java, is the path followed when executing a program
Minimum threadsA process can contain multiple threads.Java programs have at least one thread, known as the main thread
TypesUser-level threads & Kernel-level threadsUser threads & Daemon threads.
Created/Managed byOperating SystemJava Virtual Machine (JVM) at the program’s start, when the main() method is invoked with the main thread.
CommunicationThreads can share common data & communication is easier.wait(), notify(), notifyAll() are methods used for threads to communicate.
Thread Scheduling

1) Scheduling of user-level threads (ULT) to kernel-level threads (KLT) via Light-Weight Process (LWP) by the application developer.

2) Scheduling of kernel-level threads by the system scheduler to perform different unique os functions.

The thread scheduler in java is the part of the JVM that decides which thread should run. Types:  1) Pre-emptive Scheduling, 2) Time Slicing.
SynchronizationThe most popular way of achieving thread synchronization is by using Mutexes.Implemented using monitors, synchronizing using synchronized blocks.
Implementation using modelsMany-to-One, One-to-One, Many-to-ManyGreen Thread model (many-to-one model), Native Thread Model (many-to-many model)
Deadlock detection

1) If resources have a single instance

2) If there are multiple instances of resources

1) nested synchronized block or trying to get a lock on a different object or calling a synchronized method from another synchronized method

2) to use the io portal. It allows us to upload a thread dump and analyze it.

3) can also use jConsole or VisualVM to detect deadlock

Deadlock avoidanceCan be done with Banker’s Algorithm.

1) Avoid Unnecessary Locks



2) Avoid Nested Locks

3) Using Thread.join() Method

4) Use Lock Ordering

5) Lock Time-out

另外,看看不同的线程状态:

操作系统中的线程状态

线程在任何时刻的各种状态