Java Multi-Threading

Source: Internet
Author: User
Tags thread class

First, multithreading introduced

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/89/D4/wKioL1gfHYbBGxESAAA9r5caMKg696.png "title=" Small q-20161106200913.png "alt=" Wkiol1gfhybbgxesaaa9r5camkg696.png "/>


Then, multithreading is a program that has multiple execution processes. Similarly, a single thread is a program with only one execution flow.


Ii. Processes and Threads

2.1 To understand multithreading, you must understand the thread, and to understand the thread, you must first understand the process, because the thread is dependent on the process and exists.


2.2 What is a process?

With the Task Manager windows comes with, we see the existence of the process.

By observing, we know that only the running program will appear.

Process: Is the program that is running. The system is a separate unit for resource allocation and scheduling. Each process has its own memory space and system resources.


What is the meaning of more than 2.3 processes?

A single-process computer can only do one thing, such as in a DOS system.

And we now have a computer that can do more than one thing. Play the game (process) while listening to music (music process). This means that the current computer is multi-process support, that is, in a time period to perform multiple tasks, improve the efficiency of CPU usage.


What is a 2.4 thread?

Multiple tasks can be performed within the same process, and each of these tasks can be considered a thread.

A thread is the execution unit (execution path) of a process. is the most basic unit of the CPU used by the program.

Single thread: If the program has only one execution path.

Multithreading: If the program has more than one execution path.


What does 2.5 multi-threading mean?

The existence of multithreading, not to improve the execution speed of the program, in fact, to improve the application usage.

The implementation of the program is actually in the grab CPU resources, that is, the CPU execution right. Multiple processes are robbing this resource, and one of those processes has a higher chance of grabbing CPU execution if the execution path is more.

Multithreading gives us an illusion: Let's assume that multiple threads are executed concurrently. Actually, it's not. Because multiple threads share resources (heap memory and method area) of the same process, the stack memory is independent, one thread at a station. So they are still in the scramble for CPU resources to execute. A point-in-time has and only one thread executes, and whoever grabs it, this does not necessarily, so, causes the randomness of the thread to run.

We cannot guarantee that a thread can be robbed at that moment, so the execution of the thread is random.


2.6 Concurrency and parallelism?

Concurrency: Refers to a logical simultaneous occurrence, which refers to running multiple programs at the same time in a certain period .

Parallel: Refers to the physical simultaneous occurrence, refers to a certain point in time to run multiple programs.


2.7 For example, God Horse is a process, God horse is thread?

Thunder Download Tool.

When we start the Thunder this application, at this time the Thunderbolt program can become a process, then, we use Thunder Download tool is not able to download a lot of "small movie" It, Hey, is mv Oh, then this time, every download of that boom is thread. If we do not start Thunderbolt this application (Thunderbolt process), how can we download several resources at once. Therefore, the thread is dependent on the process that exists, the process is raw, the process dies. Feel a little "obedient", 650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0002.gif "alt=" J_0002.gif "/>.


Third, the Java program operating principle

The Java command launches the Java Virtual machine and starts the JVM. equals the start of an application, that is, a process is started. The process automatically starts a "main thread" and then the main thread calls the main method of a class. So the main method runs in the main thread.


Iv. is the startup of the JVM virtual machine single-threaded or multithreaded?

Multi-threaded.

Because garbage collection threads also need to be started first, memory overflow can easily occur.

Now the garbage collection thread is added to the previous main thread, starting with a minimum of two threads.

Therefore, the startup of the JVM is multithreaded.


Five, Java program implementation of multi-threaded way One

package a;/** *  Requirements: We want to implement multi-threaded program.  *  How to achieve it?  *  because threads are dependent on processes, we should go to create a process.  *       and the process is created by the system, so we should call the system function to create a process.  *      java can not directly invoke the system function, so we have no way to directly implement multithreaded programs.  *       but what? Java can invoke a program written by C + + to implement multithreaded programs.  *       lets the system function creation process be called by C + + and then by Java to invoke such things.  *       while Java provides some classes for us to use, we can implement multithreaded programs.  *  What are the classes provided by Java?  * Thread *  through the API, we know there are 2 ways to implement multithreaded programs.  *  method One, inherit the thread class  *  step:  * 1. The custom class Mythread inherits the thread class  * 2. Rewrite run in the Mythread class ()  *      3. Create object  *      4. Start Thread  *  *//* *  This class wants to rewrite the run () method, why?  *  not all code in the class needs to be executed by the thread.  *  at this point in order to differentiate between those code that can be executed by threads, Java provides the run () method in the thread class to contain code that is executed by the thread.  *  *  */class mythread extends thread{@Overridepublic  void run ()  {//in general, code executed by threads is a time-consuming for (int x = 0;x <10;x++) {System.out.println (x);}}} Public class mythreaddemo {public static void main (String[] args)  {// Create thread Object Mythread m1 = new mythread ();//Start thread m1.start ();//Create Thread object mythread m2 =  New mythread ();//Start thread M2.start ();}}


Get the default name of the thread object

Public final String GetName ()

package a;/** *  Requirements: We want to implement multi-threaded program.  *  How to achieve it?  *  because threads are dependent on processes, we should go to create a process.  *       and the process is created by the system, so we should call the system function to create a process.  *      java can not directly invoke the system function, so we have no way to directly implement multithreaded programs.  *       but what? Java can invoke a program written by C + + to implement multithreaded programs.  *       lets the system function creation process be called by C + + and then by Java to invoke such things.  *       while Java provides some classes for us to use, we can implement multithreaded programs.  *  What are the classes provided by Java?  * Thread *  through the API, we know there are 2 ways to implement multithreaded programs.  *  method One, inherit the thread class  *  step:  * 1. The custom class Mythread inherits the thread class  * 2. Rewrite run in the Mythread class ()  *      3. Create object  *      4. Start Thread  *  *//* *  This class wants to rewrite the run () method, why?  *  not all code in the class needs to be executed by the thread.  *  at this point in order to differentiate between those code that can be executed by threads, Java provides the run () method in the thread class to contain code that is executed by the thread.  *  *  */class mythread extends thread{@Overridepublic  void run ()  {//in general, code executed by threads is a time-consuming for (int x = 0;x <10;x++) {System.out.println (This.getname () + ":" +x);}}} Public class mythreaddemo {public static void main (String[] args)  {// Create thread Object Mythread m1 = new mythread ();//Start thread m1.start ();//Create Thread object mythread m2 =  New mythread ();//Start thread M2.start ();}}

Set the name of the thread object

Public final void SetName (String name)

package a;/** *  Requirements: We want to implement multi-threaded program.  *  How to achieve it?  *  because threads are dependent on processes, we should go to create a process.  *       and the process is created by the system, so we should call the system function to create a process.  *      java can not directly invoke the system function, so we have no way to directly implement multithreaded programs.  *       but what? Java can invoke a program written by C + + to implement multithreaded programs.  *       lets the system function creation process be called by C + + and then by Java to invoke such things.  *       while Java provides some classes for us to use, we can implement multithreaded programs.  *  What are the classes provided by Java?  * Thread *  through the API, we know there are 2 ways to implement multithreaded programs.  *  method One, inherit the thread class  *  step:  * 1. The custom class Mythread inherits the thread class  * 2. Rewrite run in the Mythread class ()  *      3. Create object  *      4. Start Thread  *  *//* *  This class wants to rewrite the run () method, why?  *  not all code in the class needs to be executed by the thread.  *  at this point in order to differentiate between those code that can be executed by threads, Java provides the run () method in the thread class to contain code that is executed by the thread.  *  *  */class mythread extends thread{@Overridepublic  void run ()  {//in general, code executed by threads is a time-consuming for (int x = 0;x <10;x++) {System.out.println (This.getname () + ":" +x);}}} Public class mythreaddemo {public static void main (String[] args)  {// Create thread Object Mythread m1 = new mythread (); M1.setname ("Thread 1");//Start thread m1.start ();//Create Thread object MyThread  m2 = new mythread (); M2.setname ("Thread 2");//Start thread M2.start ();}}

The

can actually be constructed to give the thread a name

package a;/** *  Requirements: We want to implement multi-threaded program.  *  How to achieve it?  *  because threads are dependent on processes, we should go to create a process.  *       and the process is created by the system, so we should call the system function to create a process.  *      java can not directly invoke the system function, so we have no way to directly implement multithreaded programs.  *       but what? Java can invoke a program written by C + + to implement multithreaded programs.  *       lets the system function creation process be called by C + + and then by Java to invoke such things.  *       while Java provides some classes for us to use, we can implement multithreaded programs.  *  What are the classes provided by Java?  * Thread *  through the API, we know there are 2 ways to implement multithreaded programs.  *  method One, inherit the thread class  *  step:  * 1. The custom class Mythread inherits the thread class  * 2. Rewrite run in the Mythread class ()  *      3. Create object  *      4. Start Thread  *  *//* *  This class wants to rewrite the run () method, why?  *  not all code in the class needs to be executed by the thread.  *  at this point in order to differentiate between those code that can be executed by threads, Java provides the run () method in the thread class to contain code that is executed by the thread.  *  *  */class mythread extends thread{public mythread () {}public mythread (string name) {super (name);} @Overridepublic  void run ()  {//in general, the code executed by the thread is more time-consuming for (int x = 0;x<10;x++) { System.out.println (This.getname () + ":" +x);}}} Public class mythreaddemo {public static void main (String[] args)  {// Create thread Object Mythread m1 = new mythread ("Thread 1"); Mythread m2 = new mythread ("Thread 2"); M1.start (); M2.start ();}}

Get the name of the thread object of the Main method

public static Thread CurrentThread ()

public class Mythreaddemo {public static void main (string[] args) {//Gets the name of the thread object of the Main method System.out.println ( Thread.CurrentThread (). GetName ());}}




Question: Why do you want to rewrite the run () method?

A: Not all code in the class needs to be executed by the thread. This time, in order to differentiate between those code that can be executed by threads, Java provides the run () method in the thread class to contain code that is executed by the thread.


Question: Which method does the startup thread use?

Answer: public void start ()


Problem: Thread can start multiple times

Answer: No, the thread can only be started once.


Question: What is the difference between the run () method and the Start () method?

A: If we instantiate a custom thread class and call the run () method at the same time, it is not the thread that is started, it is just the object invocation method, but if we instantiate the custom thread class to call the start () method at the same time, then the Java virtual Opportunity calls the thread's run () method, Started the thread.



Six, thread scheduling

If our computer has only one CPU, then the CPU can only execute one instruction at a time, and the thread only gets the CPU time slice, that is, the right to use, to execute the instruction. So how does Java make calls to threads?

A thread is a two-way scheduling model:

Time-sharing scheduling model: All threads take turns using the CPU's right of use, evenly allocating each thread to occupy the CPU of the chip.

Preemptive scheduling model: Priority for high-priority threads to use the CPU, if the priority of the thread is the same, then randomly select one, the higher priority of the thread to get the CPU time slice more than a bit, but this is only a chance.

Java uses a preemptive scheduling model.


Get the priority of a thread

Public final int getpriority ()
package a;/** *  Requirements: We want to implement multi-threaded program.  *  How to achieve it?  *  because threads are dependent on processes, we should go to create a process.  *       and the process is created by the system, so we should call the system function to create a process.  *      java can not directly invoke the system function, so we have no way to directly implement multithreaded programs.  *       but what? Java can invoke a program written by C + + to implement multithreaded programs.  *       lets the system function creation process be called by C + + and then by Java to invoke such things.  *       while Java provides some classes for us to use, we can implement multithreaded programs.  *  What are the classes provided by Java?  * Thread *  through the API, we know there are 2 ways to implement multithreaded programs.  *  method One, inherit the thread class  *  step:  * 1. The custom class Mythread inherits the thread class  * 2. Rewrite run in the Mythread class ()  *      3. Create object  *      4. Start Thread  *  *//* *  This class wants to rewrite the run () method, why?  *  not all code in the class needs to be executed by the thread.  *  at this point in order to differentiate between those code that can be executed by threads, Java provides the run () method in the thread class to contain code that is executed by the thread.  *  *  */class mythread extends thread{public mythread () {}public mythread (string name) {super (name);} @Overridepublic  void run ()  {//in general, the code executed by the thread is more time-consuming for (int x = 0;x<10;x++) { System.out.println (This.getname () + ":" +x);}}} Public class mythreaddemo {public static void main (String[] args)  {// Create thread Object Mythread m1 = new mythread ("Thread 1"); Mythread m2 = new mythread ("Thread 2"); System.out.println (M1.getpriority ());//5m1.start (); M2.start ();}}

Set the priority of a thread

Public final void setpriority (int newpriority)

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/89/DB/wKiom1gf5vCgcgcFAAAzwMEr3W8578.png "title=" Qq20161107102847.png "alt=" Wkiom1gf5vcgcgcfaaazwmer3w8578.png "/>

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M02/89/DB/wKiom1gf5yPx81CIAAAxzHufhh8006.png "title=" Qq20161107102940.png "alt=" Wkiom1gf5ypx81ciaaaxzhufhh8006.png "/>650" this.width=650; "src=" http://s3.51cto.com /wyfs02/m00/89/db/wkiom1gf53wzuhyaaaapecbpqp4165.png "title=" Qq20161107103106.png "alt=" Wkiom1gf53wzuhyaaaapecbpqp4165.png "/>

So the priority of the thread is 1-10, and the thread priority is 5, so you can explain why the above program has a result of 5.

package a;/** *  Requirements: We want to implement multi-threaded program.  *  How to achieve it?  *  because threads are dependent on processes, we should go to create a process.  *       and the process is created by the system, so we should call the system function to create a process.  *      java can not directly invoke the system function, so we have no way to directly implement multithreaded programs.  *       but what? Java can invoke a program written by C + + to implement multithreaded programs.  *       lets the system function creation process be called by C + + and then by Java to invoke such things.  *       while Java provides some classes for us to use, we can implement multithreaded programs.  *  What are the classes provided by Java?  * Thread *  through the API, we know there are 2 ways to implement multithreaded programs.  *  method One, inherit the thread class  *  step:  * 1. The custom class Mythread inherits the thread class  * 2. Rewrite run in the Mythread class ()  *      3. Create object  *      4. Start Thread  *  *//* *  This class wants to rewrite the run () method, why?  *  not all code in the class needs to be executed by the thread.  *  at this point in order to differentiate between those code that can be executed by threads, Java provides the run () method in the thread class to contain code that is executed by the thread.  *  *  */class mythread extends thread{public mythread () {}public mythread (string name) {super (name);} @Overridepublic  void run ()  {//in general, the code executed by the thread is more time-consuming for (int x = 0;x<10;x++) { System.out.println (This.getname () + ":" +x);}}} Public class mythreaddemo {public static void main (String[] args)  {// Create thread Object Mythread m1 = new mythread ("Thread 1"); Mythread m2 = new mythread ("Thread 2"); Mythread m3 = new mythread ("Thread 3"); M1.setpriority (thread.min_priority); M2.setPriority ( thread.norm_priority); m3.setpriority (thread.max_priority); M1.start (); M2.start (); M3.start ();}}

Thread 1:0

Thread 1:1

Thread 3:0

Thread 2:0

Thread 3:1

Thread 3:2

Thread 3:3

Thread 3:4

Thread 3:5

Thread 3:6

Thread 3:7

Thread 3:8

Thread 3:9

Thread 1:2

Thread 2:1

Thread 2:2

Thread 2:3

Thread 2:4

Thread 2:5

Thread 2:6

Thread 2:7

Thread 2:8

Thread 2:9

Thread 1:3

Thread 1:4

Thread 1:5

Thread 1:6

Thread 1:7

Thread 1:8

Thread 1:9

Referring to the experimental results on my machine, it can be seen that setting the priority of a thread simply increases the chance that the thread can preempt the CPU time slice.


Seven, the line program control system










This article is from the "11831428" blog, please be sure to keep this source http://11841428.blog.51cto.com/11831428/1870108

Java Multi-Threading

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.