java-Basics-Multithreading

Source: Internet
Author: User

Multithreading

Process: A process refers to a program that is running. To be exact, when a program goes into memory, it becomes a process, and the process is a program that is in the process of running and has a certain independent function.

Threads: A thread is an execution unit in a process that is responsible for the execution of a program in the current process, with at least one thread in a process, multiple threads, and this application also known as multithreaded programs.

Program Operating principle

Time-sharing scheduling: All threads take turns using CPU usage, evenly allocating CPU usage times

Preemptive scheduling: Prioritize high-priority threads to use the CPU and randomly assign rights if the thread has the same priority

In fact, the CPU (central processing unit) uses preemptive scheduling mode to switch between multiple threads at high speed. For one core of the CPU, at some point, only one thread can be executed, and the CPU switches between multiple threads faster than we feel, and looks like it is running at the same time.

In fact, multi-thread programs can not improve the speed of the program, but it can improve the efficiency of the program, so that the CPU utilization is higher.

After the JVM is started, there must be an execution path (thread) starting from the main method and executing until the main method ends, which is called the main thread in Java.

Thread Class

Create two methods to execute a new thread:

One way is to declare a class as a subclass of Thread. The subclass should override the Run method of the Thread class. Create the object to open the thread. The Run method is equivalent to the main method of another thread.

Another way is to declare a class that implements the Runnable interface. The class then implements the Run method. It then creates a subclass object of runnable, which is passed into the constructor method of a thread, and the thread is opened.

Common methods:

The void start () ---------------causes the thread to start executing, and the Java Virtual machine calls the thread's Run method

void Run () ----------------The action to be performed by the thread

static void Sleep (Long,millis) ----------allow the executing thread to hibernate within the set number of milliseconds

Create thread mode one inherits the thread class

Steps to create a thread:

1, define a class to inherit the Thread

2, overriding the Run method

3, create a subclass object, that is, create a thread object

4, call the Start method to open the thread and let the thread execute, and tell the JVM to call the Run method

 Public classDemo01 { Public Static voidMain (string[] args) {//To create a custom thread objectMyThread MT =NewMyThread ("New Thread! "); //Open new ThreadMt.start (); //executing a For loop in the Main method         for(inti = 0; I < 10; i++) {System.out.println ("Main thread!" "+i); }    }}

 Public classMyThreadextendsThread {//defines how to construct a specified thread name     PublicMyThread (String name) {//invokes the constructor of the parent class's string argument, specifying the name of the thread        Super(name); }    /*** Override the Run method to complete the logic of the thread execution*/@Override Public voidrun () { for(inti = 0; I < 10; i++) {System.out.println (GetName ()+ ": Executing! "+i); }    }}

What is the difference between a thread object calling the Run method and calling the Start method?

The thread object calls the Run method without opening the thread. The method is called only by the object. The thread object calls start to open the thread and lets the JVM call the Run method to execute in the open thread.

inherit the thread class principle

Inherit the thread class: Because the thread class is used to describe threads, a thread should have functionality. So why not just create the thread class object?

What is the purpose of creating a thread?

is to establish a separate execution path for the program, allowing the multi-part code implementation to execute concurrently. This means that the thread creates and executes the task that needs to be performed by a given thread.

The task in the thread class Run method is not what we need, only to rewrite the Run method. Now that the thread class has defined where to write the threads task (the Run method), you define the task code in the write location (Run method). So the override run method action is performed.

multi-threaded memory plots

When the executing thread's task is finished, the thread is automatically freed in the stack memory. But when all the execution threads are finished, the process is over.

Get thread name

Open threads will have their own independent run stack memory, then what are the names of these running threads? How do I get it? Since it is the name of the thread, according to the object-oriented characteristics of which object is the property and whose function, then we go to find that object is possible. Consult the API documentation for the thread class to discover that there is a way to get the currently running thread object. There is also a way to get the name of the current thread object.

Thread.CurrentThread () Gets the current thread object

Thread.CurrentThread (). GetName (); Gets the name of the current thread object

class extends Thread {  // Inherits thread    MyThread (String name) {        super(name);    }     // replication of the Run method
 Public voidrun () { for(inti=1;i<=20; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ ", i=" +i); }    }}classThreaddemo { Public Static voidMain (string[] args) {//Create two thread tasksMyThread d =NewMyThread (); MyThread D2=NewMyThread (); D.run ();//The Run method is called on the main thread without opening the new threadsD2.start ();//open a new thread and the new thread calls the Run method    }}
Implementing the Runnable Interface

Another way to create a thread is to declare a class that implements the Runnable interface, which then implements the Run method and then creates a runnable subclass object that is passed into the constructor method of a thread, opening the thread

The steps to create the thread.

1, the definition class implements the Runnable interface.

2. Overwrite the Run method in the interface.

3. Create the object of the thread class

4. Pass the subclass object of the Runnable interface as a parameter to the constructor of the thread class.

5. Call the Start method of the thread class to open the thread.

Code Demo:

 Public classDemo02 { Public Static voidMain (string[] args) {//To create a thread execution target class objectRunnable Runn =Newmyrunnable (); //passing the subclass object of the Runnable interface as a parameter to the constructor of the thread classThread thread =NewThread (Runn); Thread thread2=NewThread (Runn); //Open ThreadThread.Start ();        Thread2.start ();  for(inti = 0; I < 10; i++) {System.out.println ("Main thread: Executing!" "+i); }    }}

Custom Thread execution Task class

 Public class Implements runnable{    // Define the Run method logic to be executed by the thread     @Override    public  void  Run () {                for (int i = 0; i < i++ ) {            System.out.println ( /c17> "My thread: Executing! "+i);     }}}

the principle of realizing runnable

Why do we need to set a class to implement the Runnable interface? What is the difference between inheriting the thread class and implementing the Runnable interface?

Implements the Runnable interface, avoids inheriting the single inheritance limitation of the thread class . override the Run method in the Runnable interface to define the thread task code in the Run method.

creates an object of the thread class, and only objects that create the thread class can create threads . The thread task has been encapsulated into the Runnable interface's Run method, and the Run method belongs to the subclass object of the Runnable interface, so the subclass object is passed as a parameter to the thread's constructor, so that the thread object can be created with the task of defining the thread to run.

The second way to implement the Runnable interface avoids the limitation of single inheritance, so it is more commonly used. Implement the Runnable interface in a way that is more consistent with object-oriented, the thread is divided into two parts, a part of the thread object, a part of the thread task. Inheriting the thread class, the threading object and the thread task are coupled together. Once the subclass object of the thread class is created, it is both a threaded object and a thread-path task. Implement the Runnable interface, separate the thread tasks into objects, and the type is the Runnable interface type. The Runnable interface decouples thread objects and thread tasks.

Anonymous internal classes for threads are used

The use of internal anonymous inner classes in threads makes it easy to implement different thread task operations for each thread.

Method 1: When you create a thread object, directly override the Run method in the thread class

    New Thread () {            publicvoid  run () {                for (int x = 0; X & Lt 40; x + +) {                    System.out.println (Thread.CurrentThread (). GetName                            ()+ "... X .... "+ x);}}                }        . Start ();

Method 2: Implement the Runnable interface using an anonymous inner class and re-runnable the Run method in the interface

New Runnable () {            publicvoid  run () {                for (int x = 0; x < 40; x + +) {                    System.out.println (Thread.CurrentThread (). GetName                            ()+ "... Y .... "+ x);}}        ;         New Thread (R). Start ();

java-Basics-Multithreading

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.