Why multithreading?
. Model simplification. For example, some programs run by multiple relatively independent tasks:
The appearance of the graphic interface, the obstruction of Input and Output
. Better use of multi-core CPU
. Asynchronous behavior needs
Java multithreading features:
Main itself is a thread.
. Threads are concurrent and unordered.
The threads are executed sequentially.
. Share Data
Java multithreading risks:
. Security Risk: because the operation sequence of the thread is uncertain, some programs that can run in a single thread may encounter unexpected results under multiple threads.
. Performance risks: Server throughput, responsiveness, and resource consumption
Java multi-thread API:
Java can create threads in two forms: 1. Implement the Runnable interface and 2. inherit the Thread class.
Sample Code for inheriting thread Creation
- 0; I <10; I ++ ){
- "Main:" + I );
- 0; I <10; I ++ ){
- "Thread:" + I );
Implement runnable thread creation code
- 0; I <10; I ++ ){
- "Main:" + I );
- 0; I <10; I ++ ){
- "Thread:" + I );
Java thread pool technology: Executors obtains the exceuctorservice thread pool code
- 99 );
- "T1 ");
- "T2 ");