Java multi-thread learning notes and multi-thread learning notes
Concept:
1. Differences between concurrency and Parallelism:
Concurrency: one processor processes multiple tasks simultaneously
Parallel (Parallelism): Multiple Processors "simultaneously" process multiple tasks
2. Advantages and Disadvantages of multithreading:
Advantages of multithreading:
Tasks can be processed in parallel to reduce the waiting time of a single task.
The system overhead of a thread is smaller than that of a process or sub-process.
It is easier to share resources between threads.
CPU resources can be fully utilized in multi-core scenarios
Disadvantages of multithreading: Access conflict lock contention-deadlock-lock granularity context switching overhead synchronization/memory copy overhead
JVM part:
Tinking In Java:
1. Concurrency is deterministic but not deterministic.
2. If no task is blocked, it makes no sense to use concurrency on a single processor machine.
3. Some programming languages are designed to isolate concurrent tasks from each other. These languages are generally called function-based languages-erlang.
4. syntax sugar: while (countDown --> 0), private final int id = taskCount ++; Use the plus (+) and minus (--) pairs to add and subtract counters, which is convenient and clear.
5. Various executors ):
CachedThreadPool: generally preferred. It is created on the same number of threads.
FixedThreadPool: specifies the number of threads in advance.
SingleThreadExecutor is like a FixedThreadPool with a thread count of 1 (it provides long-term survival and concurrency assurance, and is suitable for some specific tasks ). SingleThreadExecutor serializes all tasks submitted to it.
6. If you want to return a value when the task is completed, use callable instead of runnable interface.
7.