Java Learning Lesson 22nd (Multithreading (ii))-(How to create Multithreading: inheriting the Thread Class)

Source: Internet
Author: User

A thread is a thread of execution in a program. A Java virtual machine allows an application to run multiple execution threads concurrently.

There are two ways to create a new thread of execution.

One way is to declare the class as Thread a subclass. The subclass should override Thread the method of the class run . Another way is to declare a Runnable class that implements an interface. The class then implements the run method.

Create thread mode One: Inherit the thread class


First, the steps to create the thread:

1. Define a class to inherit the thread class

2. Override the Run () method in thread

3. Directly create the object of the thread class subclass

4. Call the Start method to open the thread and invoke the thread's task to execute the Run method


/* The purpose of creating a thread is to open an execution path that runs the specified code and other code implementations concurrently
*
* Running the specified code is the task of this execution path
*
* The task for the main thread created by the JVM is defined in main function main
* Instead of customizing the thread where is its task?
* The thread class is a description of the thread, which requires a task, so the thread class also describes the task
* This task is represented by the Run method in the thread class, which is the function that encapsulates a custom thread to run the task
*
* In short: The Run method defines the task code that the thread will run
*
* The thread is turned on in order to run the specified code, so only the thread class is inherited and the Run method is replicated
* Define the running code in the Run method, which is why you should inherit the thread class
*
*/

Second, the difference between calling start and run:

Call the Start method to implement multi-threading, while calling the Run method does not implement multithreading

Start the thread with the Start method, and actually implement multi-threaded operation, without waiting for the Run method body code to complete and proceed directly to execute the following code.

calling the Run () method is just a normal way of a class, and if you call the Run method directly , the program executes the path of the main thread There is only one, so do it in order, or wait for the Run method body to finish before you can continue executing the following code

Class Demo  extends Thread{private string name;public Demo (string name) {this.name = name;} public void Run () {for (int i = 0;i<10;i++) {System.out.println (name+ "i =" +i);}}} public class Main{public static void Main (string[] args) {Demo Ademo = new Demo ("A");D emo Bdemo = new Demo ("B");//ademo.run ();//bdemo.run ();//This will only be the main thread running, the creation thread call method is the same as before we created the object call method//So use start to get the thread to execute; The Java virtual machine calls the thread's Run method. Ademo.start (); SYSTEM.OUT.PRINTLN ("SD");//sd print is random Bdemo.start ();}}

You can get the name of the thread by GetName (), Number: Thread-0 (starting from 0)

And the line Cheng was created and numbered.

public void Run () {for (int i = 0;i<10;i++) {System.out.println (name+ "i =" +i+ "Name=" +getname ())}}

How do I get the name of the currently running thread?

This method is available in the thread class

Class Demo  extends Thread{private string name;public Demo (string name) {super (name);//The name of the thread can also be customized this.name = name ;} public void Run () {for (int i = 0;i<10;i++) {System.out.println (name+ "i =" +i+ "Name=" +thread.currentthread (). GetName ( ));}}} public class Main{public static void Main (string[] args) {Demo Ademo = new Demo ("A");D emo Bdemo = new Demo ("B"); Ademo.start (); Bdemo.start (); System.out.println ("Over" +thread.currentthread (). GetName ());}}

So the name of the main thread is the main

Three, the running diagram of the thread


PS: (If the main function exists in System.out.println (1/0);) The main thread has an exception and does not affect the execution of other threads, so who has an exception who ends, the other does not affect

Iv. Status of the thread

Threads have 4 states: Created, run, frozen (let threads stop), extinct



Where the sleep method needs to specify the sleeping time, in milliseconds

Wait method, without parameters, the thread freezes, but does not die, so use the Notify () method to wake up

There is a special status: Ready, qualified for execution, but not yet acquiring resources, awaiting execution, When the start method of the thread object is called, the thread enters the ready state, but at this point the thread dispatcher has not set the thread to the current thread and is in a ready state. After a thread is running, it is ready to return from waiting or sleeping .


Temporary blocking state: When a thread is running, it is paused, usually in order to wait for a certain time to occur (for example, a resource is ready) before continuing to run. Methods such as sleep,suspend,wait can cause thread blocking.

So: running, freezing, temporary blocking, three-state graphs


A thread that wants to freeze must first have execution qualification and execution rights.

Run and freeze, run and ready can be converted to each other, but frozen and ready for the sex

A running thread that has the ability to execute the CPU and has the power to execute the CPU.

A thread that is in a frozen state , releasing the execution of the CPU, is also releasing the CPU's execution eligibility. As soon as the frozen state is complete, it is eligible for execution.

Ps:

CPU execution Eligibility: can be processed by the CPU, queued in the processing queue

CPU execution: Being processed by the CPU



Java Learning Lesson 22nd (Multithreading (ii))-(How to create Multithreading: inheriting the Thread Class)

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.