From the beginning of this article, I will be based in King of Dan and scenes from bronze , gold , platinum , masonry , star Yao to king , different Dan correspond to different degrees of difficulty , Gradually introduce concurrent programming in JAVA from the shallower to the deeper, and continue to update on Tuesdays, Thursdays and Saturdays
In terms of the knowledge system of the article, it is mainly based on practice, and the explanation of theoretical knowledge is interspersed in practice, and this article will start with the simplest thread creation.
One, a game scene
In this game, there will be 3 players playing, they are Nezha, Su Lie and Ahn'Qiraj. According to the player's different role positioning, in the Canyon of Kings, they will have different game routes:
- As a warrior, Nezha will take the confrontation route on the road;
- Mage Ahn'Qiraj went to guard the middle road;
- Zhan Tan Sulie decided to go to the bottom.
Second, the code implementation
Obviously, you have discovered that these players are definitely not single-threaded. Next, we will simulate their route through simple multi-threading. Of course, there will never be a few simple threads in a real game engine, and the situation will be much more complicated.
public static void main(String[] args) {
Thread neZhaPlayer = new Thread() {
public void run() {
System.out.println("我是哪吒,我去上路");
}
};
Thread anQiLaPlayer = new Thread() {
public void run() {
System.out.println("我是安其拉,我去中路");
}
};
Thread suLiePlayer = new Thread() {
public void run() {
System.out.println("我是苏烈,我去下路");
}
};
neZhaPlayer.start();
anQiLaPlayer.start();
suLiePlayer.start();
}
The running result of the code:
我是哪吒,我去上路
我是苏烈,我去下路
我是安其拉,我去中路
Process finished with exit code 0
The above is a simple code snippet in the game. We created 3 threads to represent 3 players, and implemented their route actions run()
method, and then started the threads start()
It is simple enough, but here are 3 knowledge points that you need to pay attention to.
1. Create thread
Thread neZhaPlayer = new Thread();
2. Execute code snippet
public void run() {
System.out.println("我是哪吒,我去上路");
}
3. Start thread
neZhaPlayer.start();
For us, creating threads is not our goal, our goal is to run the code we expect (such as the player's game route or an action) , and threads are just our way to achieve this goal. Therefore, when writing multi-threaded code, it is undoubtedly extremely important to run the specified code fragment. In Java, we mainly have 2 ways to specify:
- Inherit
Thread
and rewrite therun
method; - Implement the
Runnable
interface and pass it to the constructor ofThread
Three, two ways of thread creation
1. Inherit Thread to create a thread
In the above sample code, we are using this method, but it is an anonymous implementation, you can also inherit through explicit:
public class NeZhaPlayer extends Thread {
public void run() {
System.out.println("我是哪吒,我去上路");
}
}
In addition, in Java and higher JDK versions, you can also simplify the code through lambda expressions:
Thread anQiLaPlayer = new Thread(() -> System.out.println("我是哪吒,我去上路"));
2. Implement the Runnable interface to create a thread
The second way to create threads is to implement the Runnable
interface. We created NeZhaRunnable
class and implement Runnable
interface run
method, as shown in the following code.
public class NeZhaRunnable implements Runnable {
public void run() {
System.out.println("我是哪吒,我去上路");
}
}
Thread neZhaPlayer = new Thread(new NeZhaRunnable());
neZhaPlayer.start();
From the effect point of view, the thread effect created by the two methods is the same. So, how should we choose?
I suggest you use Runnable
For these two methods, there is no clear regulation on which is better. However, from the point of view of object-oriented design, it is recommended that you use the second method: implement the Runnable interface .
This is because, in object-oriented design, there is a conventional rule, composition is better than inheritance (Prefer composition over inheritance) , if there is no special purpose to rewrite the parent class method, try not to use inheritance. All classes in Java can only be single-inherited. Once Thread is inherited, other classes cannot be inherited, which seriously affects the expansion and flexibility of the class. In addition, the implementation of the Runnable interface can also be used in combination with the later more advanced concurrency tools.
Therefore, compared to inheriting Thread, implementing the Runnable interface can reduce the coupling between codes and maintain better flexibility. For more description of this principle, you can refer to "Effective Java".
Of course, if you have a soft spot for Thread, I didn't say it. In addition, in Java, we can also ThreadFactory
, but in essence it is still an encapsulation of these two methods.
Fourth, pay attention, don't step on the pit!
The start of the thread is simple, but for some novices, when starting the thread, they accidentally use run()
instead of start()
, like the following:
Thread neZhaPlayer = new Thread(new NeZhaRunnable());
neZhaPlayer.run();
If you call like this, you can still see the output you expect, but this is where is stuck! This is because the run()
method in Runnable is not called by the thread you created, but by the thread that called your thread, which is the main thread . Then why can I see the output even when run()
This is because the Thread of run()
directly call target in run()
:
public void run() {
if (target != null) {
target.run();
}
}
So you see, if you call run()
directly, no new thread will be created. The execution details of these two methods will be analyzed in the thread status later. Here you have to remember that the starting thread calls start()
instead of run()
.
The above is the entire content of the text. Congratulations on getting another star!
The Master's Trial
In two different ways, create two threads, print the odd and even numbers between 1 and 100, and debug with breakpoints.
About the author
Follow the public [160ae34bb52a97 mediocre technology joke ] to get timely article updates. Record technical stories of ordinary people, share technical articles with quality (as much as possible), and occasionally talk about life and ideals. Don't sell anxiety, don't sell courses.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。