This is the 21st day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
concurrent
- in
java
There are many ways to implement a concurrency in- Like implementing a
Runable
interface
- Like implementing a
public class testRunable implements Runnable{
@Override
public void run(a) {
System.out.println("test"); }}Copy the code
run
Method code is executed in a thread summary,- The execution of threads is mainly a few simple instructions provided by the operating system
- There is no need to go task by task and thread by thread, which is a huge waste of resources
- If we use thread pools, see the following figure
- When we use thread pools,
newCachedThreadPool
It creates a lot of short tasks- Each task will then be executed on an idle thread
Create a thread
- Itself in
Java
There are three ways to create a thread in- inheritance
Thread
class - implementation
Runable
interface - use
FutureTask
- inheritance
1.Thread
- Call with a class object
start()
Start the thread- The process of starting is to get
CPU
Resources, and then actually change to the running state
- The process of starting is to get
2.Runable
- Return without tasks
3.FutureTask
- Code implementation
call
methodsFutureTask
The object’sget()
The method is to wait for the task to complete and return the result
The thread pool
- Thread pools are born for a number of reasons
- First let’s think about single-threaded
Executor
If a task commits another task to the sameExecutor
- However, waiting for the result of the first task to commit occurs, so this often causes deadlocks
- First let’s think about single-threaded
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
Copy the code
- The core base size, maximum number of threads, and lifetime of a thread pool are all responsible for thread creation and destruction
- More threads are created when the work queue is full
- But if a thread exceeds its lifetime, it will definitely be recalled