Multithreading in Java

I. 【Multithreading in Java】Introduction


Hello everyone, I'm Cabbage, a sophomore. This article is an introduction to the basics of Java - multithreading. After reading this article, what can you guys gain?

The difference between a program, a process, and a thread
Four ways to create threads
Common methods of threading
Thread deadlock, release lock
Thread synchronization principle, life cycle, etc.
Not much nonsense, full of dry goods, come and have a look~

2. 【Multithreading in Java】 Basic Concepts


What is a program?

A program is a collection of instructions written in a language to accomplish a specific task. In the vernacular, it is the code we write
What is a process?

A process is an execution of a program, or a program that is running. For example, running QQ, WeChat, running MP3 players, etc., have their own processes of generation, existence and demise
What is a thread?

A thread is created by a process and is an entity of a process. A process can have multiple threads or a single thread


3. 【Multithreading in Java】Create a thread


1. Method 1
Inherit the Thread class and see the code:

public class Thread_one {
public static void main(String[] args) throws InterruptedException {
Person person = new Person();
person.start();
//When starting a thread, the child thread and the main thread will execute alternately
//The main thread ends, the child thread does not necessarily end
//person.run() is a normal method, it does not actually start a thread
for (int i = 0; i < 20; i++) {
System.out.println("main thread execution");
Thread.sleep(1000);
}
}
}
class Person extends Thread {
@Override
public void run() {
int times = 0;
while (true) {
try {
System.out.println("Hello everyone, I'm cabbage~"
+ (++times)
+ "Number" + "Thread name is—"
+ Thread.currentThread().getName());
Thread.sleep(2000);
if (times == 50) break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}


The function of this code is: start a child thread, print "Hello everyone, I'm cabbage" on the console 50 times, the main thread prints "main thread execution" on the console, and some of the running results are as follows:

Let's focus on analyzing this creation method, because the latter three methods are not fundamentally different.

When our Person class inherits the Thread class, we need to rewrite run() and write the code logic we need in the method body. The statement Thread.sleep(2000); means that after each sentence is printed on the console, the child thread will "rest" for 2 seconds. During this "rest" time, the main thread will start executing its own statement; similarly, in When the main thread "rests", the child thread also starts to execute its own statement.

In short, the child thread and the main thread will be executed alternately, and it can be found that after the main thread ends, the child thread does not necessarily end. Special attention is required here.

Thinking friends may have to ask: We have rewritten run() in the Person class, but when we use threads, we call start(), then who executes run()? Don't worry, let's go into the source code and take a look.

We can find from the source code that start() calls start0(), and start0() is a local method called by the JVM, but we can't see it.


2. Method 2
Once the method is understood, let’s look at the second method. The code is as follows:

public class Thread_two {
public static void main(String[] args) {
Animal animal = new Animal();
Thread thread = new Thread(animal);
thread.start();
}
}
class Animal implements Runnable {
int times = 0;
@Override
public void run() {
while (true) {
System.out.println("Hello everyone, I am Tomcat~");
try {
Thread.sleep(2000);
++times;
if (times == 10) break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}


The logic of this code is also easy to understand, so I won't go into too much detail here. Let's analyze: Why use a class to implement an interface to create a thread?

Friends who have learned the basics know that our Java is single inheritance. Therefore, in some cases, a class may have inherited a class, and then it is not possible to create a thread by inheriting the Thread class method, so we have the Runnable interface.

3. Method three
Let's look at the third way, the code is as follows:

public class Thread_six {
public static void main(String[] args) throws Exception {
D d = new D();
FutureTask futureTask = new FutureTask(d);
Thread thread = new Thread(futureTask);
thread.start();
Object o = futureTask.get();
System.out.println(o);
}
}
class D implements Callable {
@Override
public Object call() throws Exception {
int sum = 0;
for (int i = 0; i < 5; i++) {
System.out.println(i + 1);
sum += i;
}
return sum;
}
}

Let's see the running result:

Compared with the Runnable class, the class Callable is more powerful, and has the following advantages:

Compared to the run() method, it can have a return value
methods can throw exceptions
Generic return value support
Need to use the FutureTask class, such as getting the return result
4. Method four
Finally, let's take a look at the fourth method, using the thread pool, which is also the most recommended method. The code is as follows:

public class Thread_seven {
public static void main(String[] args) {
ExecutorService service =
Executors.newFixedThreadPool(10);
// service can be understood as a pool
service.execute(new F()); //Applicable to Runnable
// service.submit(); // for Callable
service.shutdown();//Close the thread pool
}
}
class F implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(i + 1);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}


The result of running is without any problems:


4. Common methods
1. The first group
public Thread(Runnable target): Returns a reference to the currently executing thread object
public synchronized void start(): start the thread
public final synchronized void setName(String name): Set the thread name
public final void setPriority(int newPriority): Set the priority level of the thread
public static native void sleep(long millis): Set the sleep time of the thread
public void interrupt(): Interrupts the thread, but does not end the thread, generally used to interrupt the thread that is sleeping
So many methods, practice with code:

public class Thread_five {
public static void main(String[] args) {
A a = new A();
Thread thread = new Thread(a);
thread.setName("Lollipop thread");
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
thread.interrupt();
for (int i = 0; i < 20; i++) {
System.out.println("Main thread starts action");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class A implements Runnable {
@Override
public void run() {
while (true) {
try {
for (int i = 0; i < 10; i++) {
System.out.println("I want to eat" + (i + 1) +
"Lollipop, the thread is:"
+ Thread.currentThread().getName());
}
System.out.println("Eat too much, it will take 20 seconds to digest");
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}


Let's take a look at the priority of the thread:

MAX_PRIORITY: 10
MIN_PRIORITY: 1
NORM_PRIORITY: 5
Intercept a part of the running result:

Analysis: Since the priority of the sub-thread is set to the lowest, the main thread gets the statement to be executed first, and outputs "main thread starts to act", and then when the main thread sleeps, the sub-thread starts to execute, and when the execution is finished: eat more Now, when you want to digest 20 seconds, you should wait for 20 seconds, but interrupt() interrupts the child thread, so the above picture will appear.

If the statement thread.interrupt(); is deleted, the following result will appear:


Copyright statement: The content of this article is contributed by Alibaba Cloud real-name registered users. The copyright belongs to the original author. The Alibaba Cloud developer community does not own the copyright and does not assume the corresponding legal responsibility. For specific rules, please refer to the " Alibaba Cloud Developer Community User Service Agreement " and " Alibaba Cloud Developer Community Intellectual Property Protection Guidelines ". If you find any content suspected of plagiarism in this community, fill out the infringement complaint form to report it. Once verified, this community will delete the allegedly infringing content immediately.

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00