Java Multithreaded Programming Tutorial

Source: Internet
Author: User

The meaning of multithreaded programming: The program task is divided into several parallel sub-tasks, especially in network programming, many functions are to be executed concurrently. This lesson will be explained in terms of thread concepts, development methods, and operations.

    • Thread concept: includes process and thread differences, thread concept, run state, and priority

    • Thread development method: Inherit thread and implement Runnable, timer timbertask and thread group Threadgroup and Threads pool

    • Thread run: Thread start, stop, Hibernate, suspend, sync mechanism


First, the concept of threading

1. The difference between a process and a thread

a) process. Many processes can be created in most operating systems. Whenever a program is started, it can create a process for each task that is about to start and allow them to run concurrently. When one program is blocked, another process can also run to increase resource utilization. Each process consumes a significant portion of the processor time and memory resources. Communication between processes is inconvenient.

b) thread. Threads also become lightweight processes. Because threads can only be active within the scope of a single process, creating a line turndown creates a process that is inexpensive. Threads allow collaboration and exchange of data. Threads require the support of the operating system, not all machines provide threads.

2, the concept of threading

Threads are sub-tasks that are independent of each other and can run independently, and each thread has its own call stack. All multitasking is done by periodically switching CPU time slices to different subtasks, although on the microscopic level, only one sub-task is run on a single-core CPU, but from a macro point of view, each sub-task appears to be running continuously at the same time.

Most of the operating systems we use today are multi-tasking, time-sharing operating systems. It is because of this operating system that the emergence of multi-threaded concept.

3, the running state of the thread

In Java, multithreading is a class or a program that executes or manages the ability of multiple threads to perform tasks, and each thread can run independently of other threads, but can also run in collaboration with other threads, and a class that controls all of its threads to determine which thread has priority. That thread can access the resources of other classes, which thread begins execution and which thread stays dormant. The threading mechanism is as follows:

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/80/01/wKiom1c0B4fSFtAIAABgSQmFD3s210.png "title=" QQ picture 20160512123246.png "alt=" Wkiom1c0b4fsftaiaabgsqmfd3s210.png "/>

The state of a thread represents the activity that the thread is doing and the tasks it can accomplish during this time period. Line threads is created, operational, running, blocked, and dead in 5 state. A thread of life that is always in the 5 state.

    • New state: After creating a thread with new, the thread is simply an empty object and the system is not assigned a resource, saying that the thread is in the created state

    • Operational status: After starting a thread with the start () method, the system allocates the required resources except the CPU for the thread, which is in a running state (Runnable)

    • Running state: The Java runtime selects a runnable thread to occupy the CPU and turn it into running (Running) by scheduling, at which point the system actually executes the thread's run () method

    • Blocking state: A running thread cannot continue for some reason, into a blocking state

    • Death Status: Thread End

4. Priority of Threads

Conceptually, threads are run concurrently, but from a computer's point of view, they are executed serially. When the system has only one CPU, threads are executed in some order, which is called thread scheduling.

Java uses a simple, fixed scheduling method, that is, fixed-priority scheduling. This algorithm implements scheduling based on the relative priority of the thread that is in a running state. When a thread is generated, it inherits the priority of the original thread. The priority can be modified when needed. If two threads have the same priority, they will be run alternately.

The thread scheduling algorithm for a Java real-time system is still mandatory, and at any given time, if a thread state that is higher than the other thread's priority becomes executable, the system will select a high-priority thread to run.

At the same time, if multiple threads are in a running state, they need to queue up for CPU resources. At this point each thread automatically follows the priority of getting the thread, and the priority of the thread reflects the thread's importance or just Chengdu. The running state of the thread is queued by priority, and thread scheduling is based on the priority "first-come-first-serve" principle.

The thread dispatch manager is responsible for the allocation between thread queuing and CPU threads, and is dispatched by the thread scheduling algorithm. When the thread dispatch manager selects a thread, the thread obtains CPU resources and enters the operational state. Thread scheduling is a first-in-class dispatch, that is, if a more advanced thread enters the operational state during the execution of the current thread, the thread is scheduled to execute immediately. The first-occupied type of clothing is divided into: exclusive and time-sharing.

Exclusive: The current execution thread will continue to execute until the execution is completed or, for some reason, the CPU is actively discarded, or the CPU is preempted by a more advanced thread.

Time-sharing: The current running thread gets a slice, and when the time is up, even if it is not finished, let the CPU go into the operational state, wait for the next time slice to be dispatched, and the system will select another thread that can run. Time-sharing system enables each thread to work on several steps, enabling multiple threads to run simultaneously.

Second, the thread development method

Threads all operations occur in the thread body, in the Java midline Cheng is the Run method inherited from the thread class or the class that implements the Runnable interface, and when the thread is generated and initialized, the real-time system calls its run method. The code within the Run method implements the behavior of the thread, which is the main part of the thread.

This section will first explain the two methods of multi-process scheduling in Java programs

Using the runtime class

Using the Processbuilder class

And then we'll explain two ways to implement a thread in Java

Implement the Runnable interface to implement its Run method

Inherit the thread class, overwriting its Run method

The difference between the two ways, if you have inherited other classes, then you can only choose to implement the Runnable interface, because Java is a single inheritance relationship

1. Invoking Java programs with inheritance

Sometimes we start multiple Java sub-processes in Java code for the sake of system stability. We can implement this requirement in two ways. The simplest is to execute the Java class name through the runtime and Exec methods. If the execution succeeds, a process object is returned, and if execution fails, a IOException error is thrown. Using Processbuilder to establish a child process, call the Processbuilder Start method to start the child process, the rest of the runtime exception.

2. Creating Java Threads with inheritance

Thread is a concrete class, not an abstract class, which encapsulates the behavior of a thread.

public class Thread extends Object implements Runable

A thread is a thread of execution in a program. A Java Virtual machine allows an application to run multiple execution threads concurrently. Each thread has priority, and the execution of the high-priority thread takes precedence. Each thread can be marked as a daemon thread.

For example, a thread that calculates a prime number that is larger than a specified value

Class Primethread extends thread{long minprime;    Primethread (Long minprime) {this.minprime = Minprime; } public void Run () {//compute primes larger than minprime}}primethread p = new Primethread (143);p. Start ();

When creating a thread with inheritance, you can start with the thread's Start method.

3. Creating a Java thread using the implementation runable interface

Runable the interface class should be executed by a thread to perform its instance

This article is from the "Ah Cool blog source" blog, please make sure to keep this source http://aku28907.blog.51cto.com/5668513/1772683

Java Multithreaded Programming Tutorial

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.