Java concurrent programming example of 1: creation and execution of threads

  • 2020-04-01 03:33:27
  • OfStack

Cut to the chase

In the IT community, whenever we talk about concurrency, we always talk about a series of threads running simultaneously on a single computer. If the computer has multiple processors or a multi-core processor, it is truly "running at the same time"; But if the computer has only one single-core processor, the "simultaneous operation" is just a facade.

All modern operating systems support concurrent execution of tasks. You can listen to music and read the news online without losing your first email. We can say that this concurrency is process-level concurrency. Inside the process, I can also see that there are many, many concurrent tasks. We call concurrent tasks running in a process threads.

Another common concept associated with concurrency is parallelism. There are some differences and connections between concurrency and parallelism. Some authors believe that executing applications in multiple threads on a single-core processor is concurrency, and that you can observe the programmer's execution; In addition, when your program runs in multiple threads on multiple processors or multicore processors, it is parallel. Other programmers consider an application to be concurrent if its threads do not execute in a predetermined order. In order to simplify the solution of the problem by using threads that execute in a certain order, this is parallel.

This chapter USES twelve examples to demonstrate how to use the Java7 API to perform some basic threading operations. You will see, in a Java program, how to create and execute threads, how to control the execution of threads, how to manipulate a set of threads as a unit, and so on.

In this section, we'll learn how to create threads in a Java program and how to run them. In a Java program, everything is Object, and so are threads. There are two ways to create a thread:

1. Inherit the Thread class and override the run() method;
2. Create a class that implements the Runnable interface, then create an object for the Thread class, then pass an instance of the class that implements the Runnable interface as an argument to the instance of the Thread class.

In this section, we'll use the second method to create ten threads and get them running. Each thread calculates and prints the product of two integers up to ten.

learning

Follow the steps described below to implement this example:

1. Create a class called Calculator and implement the Runnable interface. The code is as follows:


public class Calculator implements Runnable {

2. Declare a private plastic property named number, and implement the constructor of the class to initialize the property just declared. The code is as follows:


private int number; public Calculator(int number) {
    this.number = number;
}

3. Implement the run() method, which is the instruction that runs when the thread we created executes, so it is used to calculate The Times table. The specific code is as follows:

@Override
public void run() {
    for (int i = 0; i < 10; i++) {
        System.out.printf("%s: %d * %d = %dn",
                Thread.currentThread().getName(),
                number, i, i * number);
    }
}

4. Now it's time to implement the main class for the sample application. Create a class named Main and add the Main method to the class. The code is as follows:

public class Main {
    public static void main(String[] args) {

5. Inside the main() method, create a for loop that is iterated ten times. Inside the loop, create an object Calculator for the Calculator class, and an object Thread for the Thread class. Finally, the start() method of the thread object is called. The code is as follows:

for (int i = 0; i < 10; i++) {
    Calculator calculator = new Calculator(i);
    Thread thread = new Thread(calculator);
    thread.start();
}

6. Run this program to see how different threads execute concurrently.

Know why

The following is the output that the console prints when the program runs, and we can see that all the threads we created are executing concurrently.


Thread-3: 3 * 5 = 15
Thread-0: 0 * 2 = 0
Thread-3: 3 * 6 = 18
Thread-1: 1 * 6 = 6
Thread-1: 1 * 7 = 7
Thread-3: 3 * 7 = 21
Thread-3: 3 * 8 = 24
Thread-0: 0 * 3 = 0
Thread-0: 0 * 4 = 0
Thread-3: 3 * 9 = 27
Thread-1: 1 * 8 = 8

All Java programs execute at least one thread. When we run the Java program, the Java virtual machine (later called the JVM) runs a thread that calls the program with the main() method.

When the start() method of the Thread object is called, another Thread is created. As many times as the start() method is called, so many threads are created.

When all threads finish executing, the Java program terminates. When the starting thread (for example, the thread executing the main() method) terminates, the remaining threads continue to execute until the computation is completed. When one of the threads calls system.exit () and requests the JVM to abort the program, all threads abort its execution.

When the run() method of the Thread object is called, the Thread is not created; Likewise, the thread is not created when the run() method of the class that implements the Runnable interface is called. The Thread is created only when the start() method of the Thread object is called.

endless

As mentioned at the beginning of this section, there is another way to create threads: inherit the Thread class and override the run() method, so that you can create an object of a subclass of Thread and then call the start() method of that object to create the Thread.


To prepare for the interview Java Information on multithreading, including this book Java 7 Concurrency Cookbook ", the explanation is very easy to understand, very suitable for the multi-threading knowledge is not much, and want to seriously learn a friend. Looked for, did not find the Chinese version, simply do their own food and clothing. So, the plan is to come up with an unofficial translation, with the title tentatively set " Java7 Concurrent sample set.

si

This article is a translation from the Java7 Concurrency Cookbook (D jago to Java7 Concurrency examples) and is intended for use only as a learning material. Not to be used in any commercial activities without authorization.

Small has becomes

The original book does not have complete code, is not conducive to view. So, grug added a section dedicated to showing the full version of the code shown in this section.

The complete code for the Calculator class


package com.diguage.books.concurrencycookbook.chapter1.recipe1; /**
 * Date: 2013-09-13
 * Time: 21:42
 */
public class Calculator implements Runnable {
    private int number;     public Calculator(int number) {
        this.number = number;
    }     @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.printf("%s: %d * %d = %dn",
                    Thread.currentThread().getName(),
                    number, i, i * number);
        }
    }
}

The complete code for the Main class


package com.diguage.books.concurrencycookbook.chapter1.recipe1; /**
 * Date: 2013-09-13
 * Time: 19:46
 */
public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            Calculator calculator = new Calculator(i);
            Thread thread = new Thread(calculator);
            thread.start();
        }
    }
}


Related articles: