Article Directory
Processes and threads
- Process A
process is a collection of programs. For example , when runningQQ
,微信
etc., there are processes at runtime.
A process can contain multiple threads. (A process contains at least one thread.)
- Thread
In an application, the smallest unit of program execution flow.
The above statement is too abstract, for example:
Train == Process
Carriage == ThreadTrains and trains are different processes.
But a train can contain multiple carriages.
How many threads are there in Java?
Two by default.
One is the main thread (such as main()), and the other is the GC garbage collection thread of the jvm.
Can Java start threads?
Unable to open.
The execution of new Thread().start(); is that start0() is called in the source code; it is a C++ code logic, not Java itself.
private native void start0();
Concurrency and parallelism
- Concurrently,
multiple threads operate on the same resource. For example: grab tickets. - Parallel (CPU multi-core only)
between threads and threads can be carried out at the same time. (Two parallel trains)
Thread status
In java, java.lang.Thread.State
the following definitions are made for the state value:
public enum State {
// 新生
NEW,
// 运行
RUNNABLE,
//阻塞
BLOCKED,
//等待(死等)
WAITING,
//超时等待(期限等待)
TIMED_WAITING,
// 终止、消亡
TERMINATED;
}
The difference between wait() and sleep()
- Comes from different classes
wait() comes from the Object class, sleep() comes from the thread class.
- Regarding the release of the lock
wait() will release the lock, sleep() will not release - The scope of use is different
wait(): must be同步代码块
used in.
sleep(): No range limit. It can be anywhere.
TimeUnit.SECONDS.sleep(1);
- About exception capture
sleep needs to capture exceptions.
wait also needs to catch exceptions.