Multithreading has been the difficulty in Java development, but also in the interview of frequent, while there is still time, I intend to consolidate the JUC knowledge, I think the opportunity is everywhere, but is always left to prepare for the people, I hope we can come on!!
Go down, come up again, I think we’ll be different.
Let's take a look at a picture, calm down, and move on
JUC series
- What is JUC?
- JUC series (ii) Review Synchronized keyword
- JUC series (three) Lock Lock mechanism detail code theory combined
- The thread safety problem of JUC series (4)
- JUC series (5) | Synchonized keywords to further explain
- JUC series (6) | Callable and interface explanation & use, FutureTask application Future
- JUC series (7) | JUC three commonly used tools CountDownLatch, CyclicBarrier, Semaphore
- JUC series (8) | read-write lock – ReadWriteLock
Is being continuously updated…
I. Introduction to JUC
JUC is essentially our shorthand for the java.util.Concurrent toolkit in the JDK. This package is full of Java processing thread-related classes that have been around since jdk1.5.
Processes and threads
2.1, processes,
Summary:
Process is a running activity of a program on a data set in a computer. It is the basic unit of resource allocation and scheduling in the system and the basis of operating system structure. In modern thread-oriented computer architectures, processes are containers for threads. A program is a description of instructions, data and their organizational form, while a process is an entity of the program.
Definition:
Narrowly defined: A process is an instance of a computer program that is being executed.
Broad definition: a process is a program with some independent function about a data set of a running activity. It is the basic unit of dynamic execution of operating system. In traditional operating system, process is both the basic unit of allocation and the basic unit of execution.
2.2, thread
A thread is the smallest unit in which an operating system can schedule operations. It is contained within the process and is the actual operating unit of the process. A thread is a single sequential flow of control in a process, and multiple threads can be concurrent in a process, each performing a different task in parallel.
Threads are the basic unit of independent scheduling and dispatch. 2. Multiple threads in the same process share all system resources in the process. 3. A process can have many threads, each performing different tasks in parallel. It can be executed concurrently.
Of course, we all know that Java thread synchronization is the difficulty of Java multithreaded programming, because to give where are shared resources (competing resources), when to consider synchronization, etc., are the difficulties in programming. 😭 so there are so many drop locks, see annoying.
2.3. Three common ways to create threads
- Thread threads are created by implementing the Runnable interface
public class TheardCreateDemo {
public static void main(String[] args) {
Runnable runnable = new SomeRunnable();
Thread thread1 = new Thread(runnable);
thread1.start();
//lamda expression
Thread thread2 = new Thread(() -> {
System.out.println("Using the LAMda expression scheme"); }); thread2.start(); }}class SomeRunnable implements Runnable
{
@Override
public void run(a)
{
System.out.println(Thread.currentThread().getName()+":: Create Thread threads by implementing the Runnable interface"); }}Copy the code
2. Create a Thread by inheriting the Thread class
public class TheardCreateDemo {
public static void main(String[] args) {
SomeThread thread = newSomeThread(); thread.start(); }}class SomeThread extends Thread{
@Override
public void run(a) {
System.out.println("Create a Thread by inheriting the Thread class"); }}Copy the code
3. Create threads by implementing the Callable interface
public class TheardCreateDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Object> futureTask = new FutureTask<Object>(new SomeCallable<Object>());
Thread oneThread = new Thread(futureTask);
oneThread.start();
// Here we can get the return value after the runSystem.out.println(futureTask.get()); }}class SomeCallable<Object> implements Callable<Object> {
@Override
public Object call(a) throws Exception {
System.out.println("Create Thread threads by implementing the Callable interface");
// If (1024) = 1024
return (Object)"Well, this is something that can return data so I'm just going to return whatever I want."; }}Copy the code
And we’ll talk about that in a future article.
Here are the steps:
} Step 1: Create a SomeCallable class that implements the Callable interface
Step 2: Create a class object: Callable oneCallable = new SomeCallable();
Step 3: Create a FutureTask object from Callable:
FutureTask futureTask= new FutureTask(oneCallable);
Note: FutureTask is a wrapper that is created by accepting a Callable and implements both the Future and Runnable interfaces. Step 4: Create a Thread object from FutureTask: Thread oneThread = new Thread(FutureTask);
Step 5: Start the thread: onethread.start ();
Why Thread(FutureTask FutureTask) can be terminated?
Constructor for Thread:
public Thread(Runnable target) {
this(null, target, "Thread-" + nextThreadNum(), 0);
}
Copy the code
Reason: Because the nesting dolls come together. 😁
public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable.Future<V>
Copy the code
The fourth way is to create a thread pool, which I’ll talk about later, but I won’t add more space here.
Concurrency and parallelism
Before we look at concurrency and parallelism, let’s take a look at serial.
1) Serial mode:
Serial mode: All tasks are performed in sequence. A serial is a task that can only be taken and executed one at a time.
Take a small example in life: is to buy a ticket at the train station, today only open this window to sell tickets, so we only have to wait until the front of the people buy, then it is our turn to buy. Get the tickets in the first order.
2) Parallel mode:
Overview: A group of programs execute at an independent, asynchronous speed, both micro and macro, together. Concurrency, by contrast, refers to the execution of two or more programs in the same time period, with temporal overlap (simultaneous in macro, sequential in micro).
Parallel mode: Parallel means that multiple tasks can be achieved and executed simultaneously.
In the past, there was only one window to sell tickets, but in recent years, there are five Windows to sell tickets, greatly shortening the time for people to buy tickets.
Parallel mode is equivalent to dividing a long queue into several short queues, so parallelism shortens the length of the task queue. However, the efficiency of parallelism is influenced by the quality of multi-process/thread coding as well as the CPU from a hardware perspective.
3) Concurrency:
Concurrency: Concurrency refers to the phenomenon that multiple programs can run at the same time. The point of concurrency is that it is a phenomenon and concurrency describes the phenomenon of multiple processes running at the same time. But really, a single core CPU can only run one thread at a time. So the “running at the same time,” said here is not really the same time have the phenomenon of multiple threads running (this is the concept of parallel), but provides a function allows users to view multiple programs running at the same time, but in fact these application process is not straddling the CPU, but according to the CPU scheduler, perform stop for a while for a while.
4) A quick summary:
Concurrency: that is, multiple threads are accessing the same resource at the same time
- Examples: SEC kill, 12306 grab home tickets, grab concert tickets…
Parallelism: Multiple tasks are executed together and then summarized
- Example: rice cooker cooking, wok cooking, two things together, (finally we together dry rice dry rice 😁)
User thread and daemon thread
User threads: Threads implemented in user programs that do not require kernel support and are independent of the operating system core. Application processes control user threads using thread libraries that provide functions for creating, synchronizing, scheduling, and managing threads.
Daemon thread: a thread that provides a common service in the background while the program is running. It serves the user thread. There is no need for upper-level logic, of course we can create a daemon thread manually. (In plain English: guarding the user thread. When the user thread dies, the daemon thread dies with it.)
The garbage collection thread, for example, is a good guardian and is not an integral part of the program. Therefore, when all non-daemon threads terminate, the program terminates, killing all daemon threads in the process. Conversely, the program does not terminate as long as any non-daemon threads are running.
To simulate this, use a simple code:
When not set as daemon thread: The main thread completes execution, but the thread we created is still not finished.
Daemon thread: Obviously, when the main thread completes, the daemon thread is forced to terminate.
SetDaemon is set to whether or not it is a daemon thread.
Five, talk to yourself
Recently, I started to learn JUC again. I feel there is a lot of Java content, but I still think I need to lay a solid foundation in order to go further.
Recently in the continuous update, if you feel helpful to you, also interested in the words, pay attention to me, let us study together, discuss together.
Hello, I am ning Zhichun, a blogger, a small seed on the way of Learning Java. I also hope that one day I can take root and grow into a tree in the sky.
Hope to share with you 😁
By the time we meet again, we have achieved something.