Java Concurrency Programming Example (i): Thread creation and execution _java

Source: Internet
Author: User
Tags terminates thread class

Straight

In the It circle, whenever we talk about concurrency, we are sure to talk about a series of threads running concurrently on a single computer. If the computer has more than one processor or a multi-core processor, then it is a real "run at the same time", but if the computer has only one single core processor, then "running at the same time" is just an appearance.

All modern operating systems support concurrent execution of tasks. You can listen to the music, while the internet to read the news, not delay the start of e-mail. We can say that this concurrency is process-level concurrency. Inside the process, I can also see many concurrent tasks. We refer to the concurrent tasks running within a process as threads.

Another common concept associated with concurrency is parallelism. There are some differences between concurrency and parallelism, and there are some connections. Some programmers (Author, as a "programmer", it is considered concurrent to execute the application multithreaded on a single core processor, and you can observe the programmer's execution, and when your program is running on multiple processors or multi-core processors in multi-threaded form, it is parallel. There are also programmers who think that if the thread of the application is not executed in a predetermined order, it is concurrency, in order to simplify the problem solution instead of using a thread, and that the threads are executing in a certain order, then this is parallelism.

This chapter will demonstrate how to use the Java7 API to perform some basic threading operations with 12 examples. You'll see how to create and execute threads in Java programs, 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 Java programs, and how to run them. In a Java program, everything is Object, and so is the thread. There are two ways to create a thread:

1. Inherit the thread class and rewrite the run () method;
2. Create a class, implement the Runnable interface, and then create an object of the thread class, and then pass an instance of the class that implements the Runnable interface as a parameter to an instance of the thread class.

In this section, we'll use the second way to create 10 threads and run them. Each thread calculates and prints a product of two integers within 10.

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 Code code as follows:

public class Calculator implements Runnable {

2. Declares a private reshaping property, named number, that implements the constructor of the class to initialize the property just declared. The code is as follows:

Copy Code code as follows:

private int number;

public Calculator (int number) {
This.number = number;
}


3. Implement the Run () method, which is the program that runs when the thread we create executes (instruction), so the method is used to compute the multiplication table. The specific code is as follows:
Copy Code code as follows:

@Override
public void Run () {
for (int i = 0; i < i++) {
System.out.printf ("%s:%d *%d =%d\n",
Thread.CurrentThread (). GetName (),
Number, I, I * number);
}
}

4. It is now time to implement the main class (main) for the example application. Create a class named Main that adds the main method to the class. The code is as follows:
Copy Code code as follows:

public class Main {
public static void Main (string[] args) {

5. Within the main () method, create a for loop that traverses 10 times, in the loop body, create an object calculator of the Calculator class, create an object thread for the thread class, and calculator as a constructor parameter. The initialization statement passed to thread. Finally, the start () method of the thread object is invoked. The code is as follows:
Copy Code code as follows:

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

6. Run this program to see how the different threads are executed concurrently.

Know the reason why

Here is a piece of output that the console prints when you run the program, and we can see that all the threads we create are executing concurrently.

Copy 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 (later called the JVM) runs a thread and invokes the program that contains the main () method.

When the start () method of the Thread object is invoked, another thread is created. How many times the start () method is invoked, the number of threads will be created.

When all threads have finished executing, the Java program terminates. (In special cases, all non-background (Non-daemon) threads perform completion) when the boot thread (such as the thread that executes the main () method) terminates, the remaining threads continue to perform until the calculation task is complete. When one of the threads calls System.exit (), when the JVM aborts the program, all threads abort its execution.

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

Endless

As mentioned at the beginning of this section, there is another way to create a thread: Inherit the thread class, override the Run () method, so that you can create an object of the thread subclass, and then call the object's start () method to create the thread.

Copy Code code as follows:

Because the preparation interview, find a bunch of Java multithreading aspects of the information, including this "Java 7 concurrency Cookbook", explained the very simple and understandable, very suitable for multithreading not much, but also want to seriously learn friends. Looked for, did not find the Chinese version, simply own hands and clothing. So, plan an unofficial translation edition, the title of the book is tentatively designated as "JAVA7 concurrent sample Set".

Copycat

This article is from the "Java 7 Concurrency Cookbook" (D-Gua to "Java7 concurrent Sample Set") translation, only as learning materials used. No authorization shall be applied to any commercial act.

Small has become

The original book has no complete code and is not conducive to viewing. So, the D-Guaraní adds a section that shows the full version of the code shown in this section.

Complete code for the calculator class

Copy Code code 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 < i++) {
System.out.printf ("%s:%d *%d =%d\n",
Thread.CurrentThread (). GetName (),
Number, I, I * number);
}
}
}

The complete code for the main class

Copy 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 < i++) {
Calculator Calculator = new Calculator (i);
Thread thread = new Thread (calculator);
Thread.Start ();
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.