Overview of processes and Threads

Source: Internet
Author: User
Tags thread class

Processes and Threads

When it comes to multithreading, you have to first talk about the concepts of processes and threads.

Process

A process can be understood as a basic unit of operation managed by the operating system. 360 browser is a process, WPS is also a process, is running in the operating system ". exe" can be understood as a process

Thread

A child task that runs independently in a process is a thread. There are a lot of subtasks running like QQ.exe, such as chat threads, buddy video threads, download file threads, and so on.

Why to use multithreading

If used properly, threads can effectively reduce the cost of developing and maintaining programs, while improving the performance of complex applications. Specifically, the advantages of threading are:

1. Leverage the power of multi-processor

Today, multi-processor systems are becoming more prevalent, and prices are falling, and there is a growing tendency to use multiple processors in the low-end servers and interrupt desktop systems, which is becoming increasingly difficult to improve performance by increasing the clock frequency, Processor manufacturers are starting to prevent multiple processor cores on a single chip. Imagine, if only a single thread, dual-core processor systems on the system can only use half of the CPU resources, 100 processors on the system will have 99% of the resources are not available. Multi-threaded programs can be executed on multiple processors at the same time, and if properly designed, multithreaded applications can increase the throughput of the system by increasing the utilization of processor resources.

2. Get higher throughput rates on single-processor systems

If the program is single-threaded, the processor will be idle when the program waits for a synchronous I/O operation to complete. In multithreaded programs, if one thread waits for the I/O operation to complete, another thread can continue to run, allowing the program to continue running during I/O blocking.

3, the simplicity of modeling

By using threads, complex and asynchronous workflows can be further decomposed into a set of simple and synchronized workflows, each running in a separate thread and interacting at a specific synchronization location. We can achieve these goals through some existing frameworks, such as Servlets and RMI, which are responsible for addressing some of the details, such as request management, thread creation, load balancing, and distributing the request to the correct application components at the right time. The developer writing the servlet does not need to know how many requests are being processed at the same time, whether the input or output stream of the socket is blocked, and when invoking the Servlet's service method to respond to a Web request, the request can be handled synchronously. It's like it's a single threaded thread.

4. Simplified processing of asynchronous events

When a server application accepts multiple socket connection requests from a remote client, it is less difficult to develop such programs if each connection is assigned its own thread and uses synchronous I/O. If an application performs a read operation on the socket and no data arrives at this time, the read will block until the data arrives. In a single-threaded application, this not only means pausing during the process of the request, but also means that the processing of all requests will stall during the time the thread is blocked. To avoid this problem, single-threaded server applications must use non-blocking I/O, but this I/O complexity is much higher than synchronous I/O and is prone to error. However, if each request has its own processing thread, the blocking that occurs when a request is processed will not affect the processing of the other requests.

How threads are Created

There are two ways of creating a thread:

1. Inherit the thread, overriding the run () method of the parent class.

Extends thread{            void for(int i = 0; i < 5; i++) {System.out.println (thread.currentthread (). GetName () + "on Run!" ); } }}
void Main (string[] args) {    new for(int i = 0; i < 5; i++) {System.out.println (thread.currentthr EAD (). GetName () + "in Run! "); }}

Look at the results of the operation:

Main is running! THREAD-0 is running! Main is running! THREAD-0 is running! Main is running! THREAD-0 is running! Main is running! THREAD-0 is running! Thread-0 is running! Main is running!

It is obvious that the main thread and the Thread-0 thread are running alternately.

It is also normal that some people may not see such a noticeable effect. The so-called multi-threading refers to the two-thread code that can run at the same time without having to wait for the code in another thread to run. For a single-core CPU, there is no real multi-threaded, at each point in time, the CPU will execute a specific code, because the CPU code time to execute quickly, so the code of two threads to perform the execution looks like the same execution at the same time. It is related to the time-sharing mechanism that how long it takes to execute a particular code. CTSS divides the CPU time into several time slices, the operating system takes the time slice as unit piece as the unit each thread's code, the better CPU divides the time slice the smaller. So not see the obvious effect is also very normal, a thread printing 5 words would have been very fast, it may be in the time slice of the completion of the execution. Therefore, the simplest solution is to increase the value of the for loop by a bit (you can also add the Thread.Sleep method to the for loop, after that).

2, realize runnable interface. is similar to inheriting from the thread class, but after implementing runnable, it is still going to start with a thread:

 public class MyThread01 implements runnable{ Public void run () {for ( int i = 0; i < 5; I++) {System.out.println ( Thread.CurrentThread (). GetName () + "in Run!" ); } }}
void Main (string[] args) {    newNew for(int i = 0; i < 5; i++) {System.out.println (thread.c Urrentthread (). GetName () + "in Run! "); }}

The effect is also obvious:

Main is running! THREAD-0 is running! Main is running! THREAD-0 is running! Main is running! THREAD-0 is running! Main is running! THREAD-0 is running! Main is running! THREAD-0 is running!

Comparison of two ways to implement multithreading

Take a look at the API for the thread class:

In fact, the thread class is also the implementation of the Runnable interface. The key to the comparison between the two implementations is the contrast between extends and implements, and of course the latter is good. Because the first, inheritance can only but inherit, implementation may be more implementation, second, the way of implementation of comparison of inheritance, but also to reduce the coupling between programs.

Therefore, the implementation of multithreading is almost always the way of using the Runnable interface. However, the following article, for simplicity, inherits the way of the thread class.

Thread state

There are six thread states in the virtual machine, defined in Thread.state:

1. Newly created state new

New but not the state of the thread that started. For example, "thread t = new thread ()", and T is a thread in the new state

2. Operational status runnable

New comes out of the thread, and the call Start () method is in the runnable state. A thread in the runnable state may be running in a Java virtual machine, or it may be waiting for the processor's resources, because a thread must obtain the CPU's resources before it can run the contents of its run () method, otherwise queued

3, blocking blocked

If a thread is waiting for a monitor lock in order to enter a synchronized block/method, then the state of the threads is blocking blocked

4, Waiting for waiting

A thread is waiting for the waiting state because it calls the wait () method of the object without the timeout, the join () method of the thread without the timeout, and the Locksupport Park () method.

5, timeout waiting timed_waiting

A thread is called by the Wait () method with the object that specifies the waiting time, the join () method of the thread, the sleep () method of the thread, the Parknanos () method of the Locksupport, Locksupport Parkuntil () method, it will be in the timeout wait timed_waiting state

6. Termination status Terminated

When a thread call terminates or the run () method finishes executing, the thread is in a signaled state. The thread in the terminating state does not have the ability to continue running

Overview of processes and Threads

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.