Java Multithreading 1: Overview of processes and Threads

Source: Internet
Author: User

Processes and Threads
first introduce the next process and thread
Process
process is the program in execution, the concept of the procedure is static, the process is the concept of dynamic.
Threads
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.
Multithreading
Multi-threading refers to the ability to run multiple different threads at the same time in a single program to perform different tasks.
The purpose of multithreaded programming is to "make the most of CPU resources", when the processing of a thread does not need to consume CPU and only deal with resources such as I/O, so that other threads that need CPU resources have the opportunity to gain CPU resources. Fundamentally, this is the ultimate goal of multithreaded programming. ,
• Multithreading helps you write efficient programs that maximize CPU utilization, keeping idle time to a minimum. This is critical for the interactive network-connected environment that Java runs on, because idle time is public. For example, the network data transfer rate is much lower than the computer processing power, and the local file system resources read and write speed is much lower than the CPU processing power. Of course, user input is also much slower than the computer. In a traditional single-threaded environment, the program
you must wait for each such task to complete before you can perform the next step-although the CPU has a lot of idle time. Multithreading allows you to get and take advantage of these idle times.
• A process can contain one or more threads
• A program that implements multiple code runs concurrently requires multiple threads to be generated
CPU randomly take the time to get our program to do this one more thing and do another
the difference between a thread and a process
• Internal data and state of multiple processes are completely independent, and multithreading is a shared piece of memory space and a set of system resources that may interact with each other.
• The data for the thread itself usually has only the register data and a stack used by the program when it executes, so the thread switching is less burdensome than the process switching.

How threads are Created

There are two ways to implement a thread, the first is to inherit the thread class, then rewrite the Run method, and the second is to implement the Runnable interface and then implement its Run method.
Put the code that we want the thread to execute into the Run method, and then start the thread with the Start method, which first prepares the system resources for the execution of the thread and then calls the Run method. When a class inherits the thread class, the class is called a thread class.

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

 Public classThreadTest { Public Static voidMain (string[] args) {MyThread1 T1=NewMyThread1 ("Thread1"); MyThread2 T2=NewMyThread2 ("Thread2");        T1.start ();    T2.start (); }}classMyThread1extendsThread { PublicMyThread1 (String name) {Super(name); } @Override Public voidrun () { for(inti = 0; I < 100; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "is running"); }    }}classMyThread2extendsThread { PublicMyThread2 (String name) {Super(name); } @Override Public voidrun () { for(inti = 0; I < 100; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "is running"); }    }}

Run results

......................... Thread2 is RunningThread1 are RunningThread1 is runningThread2 are RunningThread2 is runningThread2 are RunningThread1 is run  NingThread2 is runningThread2 are RunningThread1 is runningThread2 are RunningThread2 is RunningThread1 are RunningThread1 is RunningThread2 is runningThread2 are RunningThread2 is runningThread2 are RunningThread2 is running ........ ....... ...

As you can see, thread 1 and thread 2 run alternately.

For a single-core CPU, only one thread can execute (micro-serial) at a time, and from a macro point of view, multiple threads are executing simultaneously (macro parallel).
For a dual-core or dual-core CPU, you can really do micro-parallelism.
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 because there is only one run method in the Runnable interface

 Public classThreadTest2 { Public Static voidMain (string[] args) {Thread T1=NewThread (NewMyThread1 ()); Thread T2=NewThread (NewMyThread2 ());        T1.start ();    T2.start (); }}classMyThread1ImplementsRunnable {@Override Public voidrun () { for(inti = 0; I < 100; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "is running"); }    }}classMyThread2ImplementsRunnable {@Override Public voidrun () { for(inti = 0; I < 100; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "is running"); }    }}

Run results

........................... Thread-0 is runningthread-1 are runningthread-1 is Runningthread-0 is runningthread -1 is Runningthread-0 are runningthread-1 is Runningthread-0 is runningthread- 1 is Runningthread-0 is running ....... .... ........

Remember the anonymous inner class?

 Public classThreadTest2 { Public Static voidMain (string[] args) {//A parameter is an instance of a class that implements the Runnable interfaceThread thread =NewThread (New Runnable () { @Override Public voidrun () { for(inti = 0; I < 10; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "is running");        }            }        });    Thread.Start (); }}

Comparison of two ways to implement multithreading

 Public class Implements Runnable {}

It can be seen that the thread class implements the Runnable interface, so the Run method in the Runnable interface is implemented.

Private Runnable Target;
@Override  Public void run () {    ifnull) {        target.run ();}    }

Threads are executed by the operating system, so there are some local native methods.
Take a look at two important construction methods

 Public Thread () {    init (nullnull, "thread-" + nextthreadnum (), 0);}
 Public Thread (Runnable target) {    init (null, Target, "thread-" + nextthreadnum (), 0);}

When a thread object is generated, if no name is set for it, then the name of the thread object will be used as follows: Thread-number, the number will be automatically incremented and shared by all thread objects (because it is a static member variable).

The only way to enable threading is to call the Start method.

/*** Causes this thread to begin execution; the Java Vsan * calls the Run method of this thread. * The result is, and threads is running concurrently:the * Current thread (which returns from the call to the * Start method) an d the other thread (which executes its run method). * It's never legal to start a thread more than once. * In particular, a thread is not being restarted once it has completed execution.*/ Public synchronized voidstart () {/*** This method isn't invoked for the main method thread or ' system ' * Group threads Created/set up by the VM.     Any of the new functionality added * to this method in the future May has to also is added to the VM.     * * A Zero status value corresponds to state "NEW". */
.................
start0 ();}Private native voidStart0 ();

--When using the first method to generate the thread object, we need to rewrite the Run method because the thread class's Run method does nothing at this time.
--When using the second method to generate the thread object, we need to implement the Run method of the Runnable interface, and then use the new thread (new MyThread ()) (if MyThread has implemented the Runnable interface) to generate the thread object, then the line The Run method of the Process object invokes the Run method of the MyThread class so that the run method that we write ourselves executes.

How to stop a thread
You cannot call the Stop method to stop a thread
Recommended Use

 Public classControlThread {PrivateMyThread runnable =NewMyThread (); PrivateThread thread =NewThread (runnable);  Public voidStartthread () {Thread.Start (); }     Public voidStopthread () {runnable.stoprunning (); }}classMyThreadImplementsRunnable {Private BooleanFlag =true; @Override Public voidrun () { while(flag) {//TODO        }    }     Public voidstoprunning () {flag=false; }}
















































































Java Multithreading 1: 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.