Java multithreading Concept

Source: Internet
Author: User

 

Multithreading

Generally, threads are implemented at the system layer. Java is the first language implementation. Java provides support for multithreading design at the language level.

Program: a set of computer commands, which are stored on disks as files.

Process: an execution activity of a program in its own address space. A process is a unit of resource application, scheduling, and independent operation. Therefore, it uses running resources in the system. A program cannot apply for system resources or be scheduled by the system, it cannot be used as an independent operating unit. Therefore, it does not occupy system running resources.

Thread: a single continuous control process in a process. A process can have multiple threads.

A thread is also called a lightweight process. It has independent execution control like a process and is scheduled by the operating system. The difference is that the thread does not have independent storage space, instead, it shares a storage space with other threads in the process, which makes the communication between threads much simpler than the process.

Concurrent Programming: There is a basic concept in computer programming, that is, the idea of processing multiple tasks at the same time. Many programming problems require the program to be able to stop the work being done, to handle another problem, and then return to the main process. There are many ways to achieve this purpose. Initially, programmers used their knowledge about the underlying machine to write interrupt service programs. The suspension of the main process was triggered by hardware interruption. Although this can solve the problem, it is too difficult and cannot be transplanted, so it is time-consuming and labor-consuming to port the program to a new model of machine. Sometimes interruptions are necessary for processing time-intensive tasks, but for a large number of other problems, we just want to split the problem into multiple tasks that can be run independently ), this improves the response capability of the program. In a program, these parts run independently of each other are called threads. The above concepts are called "concurrency ". The most common example of concurrency is the user interface. By using the task, you can quickly get a response after clicking the submit button, instead of waiting until the program completes the current task.

Why multithreading?

Multithreading helps you write efficient programs with maximum CPU utilization. For example, the network data transmission rate is much lower than the CPU processing capability, and the read/write speed of local file system resources is much lower than the CPU processing capability. In the traditional single-threaded environment, your program must wait until such a task is completed before proceeding to the next step-although the CPU is idle most of the time. Java multithreading allows you to make full use of the free time. If a blocking occurs in a single-threaded program, the entire program may stop running, but this will not happen in a multi-threaded program. When a thread is blocked, other threads will run, which can greatly improve the CPU efficiency.

Java thread model

During the execution of a program, only one thread can run at a certain time. Why are we starting multiple processes or multiple threads in one process, how many processes or threads are running simultaneously? This is because, with a single CPU, the operating system decides to execute a thread in a very short time segment. After the execution of this time segment ends, the system will decide to run another thread. Because the time segment is short and frequent switching occurs, we feel like these threads are running at the same time.
Q: since there is only one thread running at a time in a single CPU, why do we need to design multiple threads? Can we design multiple processes to replace multithreading?

We should consider the portability of the program during program design. When the program is put on a multi-CPU platform, multiple threads are run simultaneously to achieve real concurrency. As to whether multi-process can be used to replace multithreading, we have already explained it.

Java thread priority

Java automatically assigns priority to each thread to determine how to treat the thread when comparing it with other threads. The thread priority is used to determine when to switch from one running thread to another. This is called "context conversion ". Java uses its own thread scheduler to schedule thread running. The Java thread scheduler is a preemptible distribution process (allocated to processes with equal CPU time for each thread ). The preemptible scheduling model means that many threads are running (waiting), but only one thread is running. This thread runs until it is terminated and enters the runable state (waiting state), or another thread with a higher priority changes to the runable state. In the latter case, low-priority threads are preemptible by high-priority threads, and high-priority threads get the chance to run.
A thread with a higher priority will seize the chance of running the lower-priority thread, but this is not absolute, A low-priority thread that is waiting for a long time may still be selected by the thread Scheduler for running. The Java thread scheduler supports preemptive scheduling of threads with different priorities, but does not support time slice rotation of threads with the same priority. However, if the operating system (for example, Windows2000) of the Java runtime system supports time slice rotation, Java also supports time slice rotation of threads with the same priority.

Main thread

All Java programs have the main thread. When a Java program starts, a thread runs immediately. This thread is usually called

Main thread of the program. Because it is executed at the beginning of the program. The importance of the main thread is reflected in two aspects:

1. It is the thread that generates other sub-threads.

2. Generally, he must complete the execution because it performs various close actions.

The main thread is controllable. It can be controlled by a thread object. You can use currentthread () to obtain the reference of this main thread. Then you can control the main thread as you control other threads.

For example:

Class currentthreaddemo {

Public static void main (string ARGs []) {

Thread t = thread. currentthread (); // in this way, the reference of the main thread is obtained.

System. Out. println ("current thread:" + T)

}

}

Thread Creation

To create multiple threads, you can use the inherited Thread class and the runnable interface.

In fact, the thread class also implements the runnable interface.

The runnable interface has a run method. All objects that implement interface runnable must implement this method to create a thread. To start this thread, you must call the run method of the object, such as the start method in the Thread class. The run () method can call other methods like the main thread, reference other classes, and declare variables. The only difference is that run () establishes another concurrent ready-made execution entry in the program. When run () returns, the thread ends. The same is true for inheriting a thread. The inherited Thread class uses the method to overload the run () method to create a thread.
The difference between thread and runnable:

Why are there two methods for creating sub-threads in Java? Which one is better? The thread class defines multiple methods that can be reloaded by the derived class. If you do not need to reload other methods of thread, it is best to implement only the runnable interface.

Use isalive () and join ()

How does one thread know that another thread has ended?

There are two ways to determine whether a thread ends:

1. You can call isalive () in the ready-made environment ().

2. Call join ().

Thread Synchronization

When two or more threads need to share resources, they need some way to determine that resources are occupied by only one thread at a certain moment. The process to achieve this is called synchronization ).

There are two methods for synchronization: synchronization block and synchronization method.

Synchronization (any object) {// synchronization Block

// Critical section to be protected

}

Principle: in Java, each object has a monitor or lock. When synchronization (OBJ) is run, the system checks whether the object obj is locked. If not, the virtual machine locks the object. Then run down. After this block is run, it will be unlocked. Only the other threads that need to share resources can be unlocked. During this period, all threads that need to share resources with this thread are suspended and waiting.

Public synchronization void tempnamefunction () {// synchronous method

// Critical section to be protected

}

Principle: When the thread enters this method, a this object is automatically generated and locked by this object. This is the same as the synchronization block, except that one is an arbitrary object and the other is a this object.

Inter-thread communication:

The thread is far away from polling, which is usually implemented by the loop of repeated monitoring conditions. Once conditions are met, appropriate actions should be taken. This wastes CPU time.

Assume that the data generator must wait for the consumer to complete the work before generating new data. In a polling system, a consumer will waste a lot of CPU cycles while waiting for the producer to generate data. Once the producer completes the work, it will start polling and waste more CPU time waiting for the consumer's work to end, which is not welcome.

To avoid polling, Java includes a mechanism for inter-process communication implemented through the wait (), notify (), and notifyall () methods. These methods are implemented using the final method in the object class. So all classes contain them. These three methods can be called only in the synchronized method.

Source:

Http://hi.baidu.com/wwwanq/blog/item/e5b4a2d592888009a08bb701.html

Related Article

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.