线程
Categories:
进程 说简单点就是我们在电脑上启动的一个个应用。它是操作系统分配资源的最小单位。
线程 是进程的子任务,是 CPU 调度和分派的基本单位,实现了进程内部的并发。
线程与进程
线程,是进程的子任务,是进程中的独立执行单元。多个线程可以共享同一个进程的资源,如内存;每个线程都有自己独立的栈和寄存器。
并发环境下, 多线程存在下述问题
- 线程之间如何确保执行顺序,实现线程之间的协调与合作? 线程通信
- 线程之间如何确保对临界资源修改不会冲突? 线程同步?
线程通信
Inter-thread communication in Java is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.
线程间通信 是一种机制,使得线程能够在执行时进行协作,通常用于解决某些线程需要等待其他线程完成任务的情况。它主要涉及线程之间的等待和通知机制,而不是同一临界区内的互斥访问。
线程同步
Synchronization is crucial for ensuring that multiple threads operate safely on shared resources. Without *Synchronization, data inconsistency or corruption can occur when multiple threads try to access and modify shared variables simultaneously. In Java, it is a mechanism that ensures that only one thread can access a resource at any given time
线程同步的重点是 保证线程安全,特别是在多个线程访问共享资源时。同步机制通过确保某个共享资源在同一时刻只能被一个线程访问来防止数据不一致或冲突。Java 中的
synchronized
关键字和ReentrantLock
都是同步机制的实现,确保线程在访问共享资源时不会发生并发冲突。
解决上述问题的方式有两种
- 共享内存
- 消息传递
Java 使用共享内存的并发模型实现线程同步与通信, 这个模型称之为 JMM JMM 决定了一个线程对共享变量的写入何时对另外一个线程可见。
引用: Geekfork