Get straight to the point
In IT circles, whenever we talk about concurrency, we are bound to talk about a series of threads running simultaneously on a computer. If there are multiple processors or a multi-core processor on this computer, then it is actually "running simultaneously"; however, if the computer has only a single-core processor, then "simultaneous running" is just Just appearances.
All modern operating systems support concurrent execution of tasks. You can listen to music and read news online without delaying the first email. We can say that this concurrency is process-level concurrency. Inside the process, I can also see that there are many concurrent tasks. We call concurrent tasks running in a process threads.
Another common concept related to concurrency is parallelism. There are some differences and some connections between concurrency and parallelism. Some programmers (Author, transliterated as "programmer") believe that executing an application with multiple threads on a single-core processor is concurrency, and you can observe the programmer's execution; in addition, when your program runs with multiple threads, When threads run on multiple processors or multi-core processors, they are parallel. There are also some programmers who think that if the threads of the application are not executed in a preset order, it is concurrency; in order to simplify the problem solution, a thread is used, and these threads are executed in a certain order, then this is parallelism.
This chapter will use twelve examples to demonstrate how to use the Java7 API to perform some basic thread operations. You will be able to see, in a Java program, how to create and execute threads, how to control the execution of threads, how to manipulate a group of threads as a unit, etc.
In this section, we will learn how to create a thread in a Java program and how to run it. In a Java program, everything is an Object, and so are threads. There are two ways to create threads:
1. Inherit the Thread class and override the run() method;
2. Create a class that implements the Runnable interface, then creates an object of the Thread class, and then passes the instance of the class that implements the Runnable interface as a parameter to the instance of the Thread class.
In this section, we will use the second method to create ten threads and run them. Each thread computes and prints the product of two integers within ten.
know it
Follow the steps described below to implement this example:
1. Create a class named Calculator and implement the Runnable interface. The code is as follows:
Copy the code code as follows:
public class Calculator implements Runnable {
2. Declare a private integer attribute named number, and implement the constructor of this class to initialize the attribute just declared. The code is as follows:
Copy the code code as follows:
private int number;
public Calculator(int number) {
this.number = number;
}
3. Implement the run() method, which is the program (instruction) that runs when the thread we created is executed, so this method is used to calculate the multiplication table. The specific code is as follows:
Copy the code code as follows:
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.printf("%s: %d * %d = %d/n",
Thread.currentThread().getName(),
number, i, i * number);
}
}
4. Now, it’s time to implement the main class of the sample application. Create a class named Main and add the main method in the class. The code is as follows:
Copy the code code as follows:
public class Main {
public static void main(String[] args) {
5. Inside the main() method, create a for loop that traverses ten times. In the loop body, create an object calculator of the Calculator class, create an object thread of the Thread class, and pass the calculator as a parameter of the constructor to the thread. initialization statement. Finally, call the start() method of the thread object. The code is as follows:
Copy the code code 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 a piece of output printed on the console when running the program. We can see that all the threads we created are executing concurrently.
Copy the code code as follows:
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 a Java program, the Java Virtual Machine (hereinafter referred to as JVM) will run a thread and call the program containing the main() method.
When the start() method of the Thread object is called, another thread is created. How many times the start() method is called, how many threads will be created.
When all threads have completed execution, the Java program will terminate. (Unless under special circumstances, all non-daemon threads are executed.) When the starting thread (such as the thread executing the main() method) terminates, the remaining threads will continue to execute until the computing task is completed. When one of the threads calls System.exit(), requesting the JVM to terminate the program, all threads terminate their execution.
When the run() method of the Thread object is called, the thread will not be created; similarly, when the run() method of the class that implements the Runnable interface is called, the thread will not be created. A thread is created only when the start() method of the Thread object is called.
never ending
As mentioned at the beginning of this section, there is another way to create a thread: inherit the Thread class and override the run() method. In this way, you can create an object of the Thread subclass and then call the start() method of the object. Create thread.
Copy the code code as follows:
Because I was preparing for the interview, I found a bunch of information on Java multi-threading, including this "Java 7 Concurrency Cookbook". The explanations are very simple and easy to understand. It is very suitable for friends who don't know much about multi-threading but want to learn it seriously. After searching, I couldn't find the Chinese version, so I decided to make enough food and clothing myself. Therefore, we plan to publish an unofficial translation, and the title is tentatively titled "Java7 Concurrency Example Collection".
Use doctrine
This article is translated from "Java 7 Concurrency Cookbook" (D Gua Ge stole it as "Java7 Concurrency Example Collection") and is only used as learning materials. It may not be used for any commercial purposes without authorization.
Small success
The original book does not have the complete code, which is not convenient for viewing. Therefore, Brother D Gua added a section to show the complete version of the code shown in this section.
The complete code of the Calculator class is as follows:
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 = %d/n",
Thread.currentThread().getName(),
number, i, i * number);
}
}
}
The complete code of Main class
Copy the code code as follows:
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();
}
}
}