Java|Java Concurrency and Multithreading
Java Concurrency Concepts
- Thread actions are implemented by using method
run
of aRunnable
interface. - Thread is scheduled to run using
start
method of aThread
class. - Thread scheduler will allocate portions of CPU time (time-slice) to excute thread actions.
- The return of method
main
orrun
terminates the thread. - Concurreny doesn't mean actual phsical parallel execution.
- In which order threads will actually perform the actions is really not predictable, this is a stochastic process.
- You can't put 2 different pieces of logic from different threads to take the same time-slice on the same CPU core.
- There is some degree of parallelism but it depends.
- You can go from whatever state to runnable state (except
terminated
) and from runnable state to whatever other state exceptNew
. - Almost every state needs to transit throught the
runnable
state. - Transitions to the running state are not immediate -- thread scheduler needs to allocate next available CPU time slot for this thread.
boolean b = thread1.isAlive();
Thread.State phase = thread1.getState();
Because of the parallelism which is behind the scenes, the state could have changed, in other words, it's not exactly up-to-date.- A thread in a
runnable
state may check if it has received an interrupt signal. - A thread that has entered a
waiting
ortimed waiting
state must catchInterruptedException
, which puts it back torunnable
state, and then decide what it should do. - How would the thread react to an interrupt signal is up to the programmer.
【Java|Java Concurrency and Multithreading】Monitor object helps to coordinate order of executions of threads.
- Any object can be used as a monitor.
- It allows threads to enter blocked or waiting states.
- It enables mutual exclusion of threads and signaling mechanisms.
synchronized
enforces exclusive access to the block of code. A thread would be blocked waiting for the previous thread to complete execution of a synchronized block before it can proceed.- If
synchronized
is used to block against static context, then all the different instances of the same class will be blocking each other against the class itself, as class context is shared among all instances.
推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- android第三方框架(五)ButterKnife
- Android中的AES加密-下
- 事件代理
- Eddy小文
- 带有Hilt的Android上的依赖注入
- Java|Java OpenCV图像处理之SIFT角点检测详解
- java中如何实现重建二叉树
- 数组常用方法一
- android|android studio中ndk的使用