Sike Java multithreading (a) --- threads brief

introduction

Previous knowledge of multithreading only new Thread or implement a runnable interface simply by using a mutex (synchronized), inter-thread communication (wait / notify) is gone, the recent review multithreading, go online to look bigwigs of the blog, only to find that I was a frog, multithreaded no entry, so hard to learn recently in a multi-threaded, the way to sum up, to facilitate future review. . . .

1. achieve thread

Here Insert Picture DescriptionHere Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description

2. Thread the six states

Here Insert Picture Description

3. The advantages of multi-threading

Better resource utilization
in program design some scenarios will be easier
to enhance the responsiveness of the program

4. disadvantage of multi-threaded

Design is more complex:
the general multi-threaded programs is more complicated than single-threaded program design. When multiple threads access shared data, this part of the code needs special attention. Interaction between threads are often very complex. Incorrect thread synchronization error generated very difficult to find, reproduce and to repair.

Context switching overhead:
when the CPU switches from one thread to execute another execution thread, it needs to store local data, the program pointer to the current thread and the like, and then load the local data, a pointer to another program thread, and finally It began execution. This switching is called "context switching" ( "context switch"). A CPU executes a thread context, and another switch to another thread context for execution. Context switch is not cheap. If not necessary, it should reduce the occurrence of a context switch.

Increase resource consumption:
thread running when need to get some resources from inside the computer. In addition to CPU, thread requires a certain amount to maintain its local stack. It also needs to occupy some operating system resources to manage threads. We can try to write a program, it created 100 threads that do nothing, just wait, and then look at the program at run time how much memory.

5. How to use Java to create multiple threads

  1. Inherit the Thread class, override the run method
  2. The relevant class implements the Runnable (run) interface, override run method.
  3. Callable implement interface (relatively use less)
  4. Use the thread pool
Published 45 original articles · won praise 3 · Views 2327

Guess you like

Origin blog.csdn.net/weixin_44046437/article/details/99099183