Welcome to the first in a series of articles on Concurrency.

Starting with this article, I’ll start with a step-by-step introduction to concurrent programming in JAVA, based on segments and scenarios in The king, from bronze, gold, platinum, brick, starshine to King, with different difficulty levels, and continue to update every Tuesday, Thursday, and Saturday.

In terms of the knowledge system of the article, it is mainly based on practice and interspersed with theoretical knowledge in practice. This article will start from the simplest thread creation.

A familiar scene

In this game, there will be three players, they are Nezha, Sulie and Angela. Depending on the player’s role, there are different paths to play in Kings Canyon:

  • As a warrior, Nezha will take the antagonist route on the road;
  • The mage Angela went to guard the middle road;
  • Battantsoret decided to go the next way.

Two, code implementation

Obviously, you can already see that these players are definitely not single-threaded. Next, we’ll simulate their route through simple multithreading. Of course, a real game engine would be far more complicated than just a few threads.

public static void main(String[] args) {
        Thread neZhaPlayer = new Thread() {
            public void run(a) {
                System.out.println("I'm Nezha, I'm going on the road."); }}; Thread anQiLaPlayer =new Thread() {
            public void run(a) {
                System.out.println("I'm Angela. I'm going to the middle."); }}; Thread suLiePlayer =new Thread() {
            public void run(a) {
                System.out.println("I'm Sue. I'm going down."); }}; neZhaPlayer.start(); anQiLaPlayer.start(); suLiePlayer.start(); }Copy the code

The result of the code:

I'm Nezha, I'm going on the road I'm Sulie, I'm going down I'm Angela, I'm going middle Process Finished with exit code 0Copy the code

Above, a simple snippet of code in the game. We created three threads representing the three players, implementing their route actions with the run() method, and then starting the thread with the start(). It’s simple enough, but here are three things to keep in mind.

1. Create a thread

Thread neZhaPlayer = new Thread();
Copy the code

2. Execute the code snippet

public void run(a) {
    System.out.println("I'm Nezha, I'm going on the road.");
}
Copy the code

3. Start the thread

neZhaPlayer.start();
Copy the code

For us, creating threads is not our goal, our goal is to run the code we want (such as the player’s game path or an action), and threads are just our way of doing that. Therefore, when writing multithreaded code, it is extremely important to run the specified code snippet. In Java, we have two main ways to specify:

  • inheritanceThreadPay equal attention to writingrunMethods;
  • implementationRunnableInterface and pass it toThreadThe constructor of.

Two ways to create threads

1. Inherit Thread to create a Thread

In the example code above, we are using exactly this approach, but it is implemented anonymously. You can also display inheritance by:

public class NeZhaPlayer extends Thread {
    public void run(a) {
        System.out.println("I'm Nezha, I'm going on the road."); }}Copy the code

In addition, in Java and later JDK versions, you can simplify the code by using lambda expressions:

Thread anQiLaPlayer = new Thread(() -> System.out.println("I'm Nezha, I'm going on the road."));
Copy the code

2. Implement the Runnable interface to create a thread

The second way to create threads is to implement the Runnable interface. We create the NeZhaRunnable class and implement the run method in the Runnable interface, as shown in the following code.

public class NeZhaRunnable implements Runnable {
    public void run(a) {
        System.out.println("I'm Nezha, I'm going on the road.");
    }
}

Thread neZhaPlayer = new Thread(new NeZhaRunnable());
neZhaPlayer.start();
Copy the code

In effect, the threads created in both ways are the same. So, what should we choose?

Runnable is recommended

There is no clear rule as to which is better or worse. However, from an object-oriented design perspective, it is recommended that you implement the Runnable interface in the second way.

This is because, in object-oriented design, it is a well-established rule to Prefer composition over inheritance, and try not to use inheritance if there is no particular purpose for overriding a parent method. In Java, all classes can only be single inheritance. Once Thread inherits, it cannot inherit other classes, which seriously affects the extension and flexibility of the class. In addition, implementing the Runnable interface can also be used in conjunction with later, more advanced concurrency tools.

Therefore, implementing a Runnable interface reduces the coupling between your code and provides more flexibility than inheriting Thread. For more information on this principle, see Effective Java.

Of course, if you have a thing for Thread, forget it. In Addition, in Java we can create threads through utility classes such as ThreadFactory, but this is essentially a wrapper around both methods.

Four, attention, don’t step on the pit!

Starting a thread is easy, but for beginners, it’s easy to accidentally start a thread using run() instead of start(), like this:

Thread neZhaPlayer = new Thread(new NeZhaRunnable());
neZhaPlayer.run();
Copy the code

If you do, you can still see the output you expect, but that’s where the catch is! This is because the run() method in Runnable is not called by the thread you created, but by the thread that called your thread, i.e. the main thread. So why do I see output when I call the run() method directly? This is because the run() in Thread calls the run() in target directly:

public void run(a) {
    if(target ! =null) { target.run(); }}Copy the code

So you see, if you call run() directly, it doesn’t create a new thread. The details of the execution of these two methods will be discussed later in the thread state, but remember that starting the thread calls start(), not run().

That’s all for the text, congratulations on another star!

The teacher’s trial

In two different ways, create two threads, print odd and even numbers between 1 and 100, and debug breakpoints.

About the author

Pay attention to the public number [technology 8:30], timely access to the article updates. Pass on quality technical articles, record the coming-of-age stories of ordinary people, and occasionally talk about life and ideals. 8:30 in the morning push author quality original, 20:30 in the evening push industry depth good article.