2018-08-25 Multithreading thread Class +runnable interface + 6 states of threads

Source: Internet
Author: User
Tags thread class

Multithreading:

Process: A process is a running program; to be precise, when a program goes into memory, it becomes a process, the process is in the process of running the program, and has a certain independent function (into the memory to run the program into a process)!

Thread: 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! A process can have more than one thread, this application can also be called Multi-thread program (thread is the execution unit, a process can include multiple threads, a program can have multiple processes)!

Single-threaded: If more than one task can only be executed sequentially (this task is completed, the next task begins to execute)! such as: to Internet cafes, cafes can only let a person on the Internet, when the person under the machine, the next person to the Internet (this task is completed, after the stack, the next task can be executed)!

Multi-threaded: Multiple tasks can be executed at the same time! such as: to Internet cafes, cafes can allow many people at the same time the Internet (a thread to build a stack, multiple stacks of tasks at the same time, the main method is a stack)!

Eight-core 16-thread CPU: One core has 16 threads!

Program Operation Principle:

Time-sharing scheduling: All threads take turns using the CPU's use, evenly allocating each thread to occupy the CPU (such as 360 security defender has 3 functions: Antivirus, computer cleanup, system repair, these three functions will be allocated by the JVM 1 microseconds of time slices, in turn execute 1 microseconds, looks like the simultaneous execution, But not really)!

Preemptive scheduling: Prioritize high-priority threads to use the CPU, if the thread has the same priority, then randomly select one (called Thread randomness), Java uses preemptive scheduling (Java uses preemptive scheduling)!

You can set the priority of a process by Windwos the task Manager of the system (CTRL key +shift +ESC key):

In fact, the CPU (central processing unit) uses preemptive scheduling mode to switch between multiple threads at high speed (allocating time slices)! For a core of the CPU, at some point, only one thread can be executed, and the CPU switches between multiple threads faster than we feel, it seems to be running at the same time, in fact, multi-threaded programs can not improve the speed of the program, but can improve the efficiency of the program, Make CPU usage higher (single core can only perform the next task after executing the task, multi-core multithreading can be performed simultaneously with multiple tasks, saving time)!

Main thread: Main method is the main thread!

After the JVM starts, there must be an execution path (thread) starting from the main method, which executes until the main method ends, which is called the main thread in Java! When the main thread of the program executes, if it encounters a loop that causes the program to stay too long at the specified location, the following program cannot be executed immediately, waiting for the loop to finish!

Thread class:

The string name of the 2nd constructor method is used to specify the name of the thread!

Common methods:

The start () method invokes the run () method after the subclass of the thread class is overridden (if the overridden run () method is invoked directly using the thread subclass's object, the thread is not turned on, or the normal object invocation method, so you want to start the thread with the start () method)!

Sleep () method: Let the thread hibernate, that is, end the process!

Emphasize:

thread T1 = new Thread ();

T1.start ();

There's nothing wrong with this, but the start () call is the run () method in the thread class, and the run () method doesn't do anything, and more importantly, the Run method doesn't define the code we need to get the thread to execute!

Each thread has a separate in-memory stack space, so it can be implemented concurrently (and involves managing high concurrency issues):

When the execution 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!

Gets the object or name of the currently executing thread:

Since this method is static, the class name can be called. Method call!

Classroom Sample Code:

 PackageCom.oracle.duoxiancheng; Public classDemo01 { Public Static voidMain (string[] args) {//Thread new threads, and the main method are threads, the main method is the main thread, in memory to enjoy the independent stack space://Create a new first thread:MyThread mt1=NewMyThread (); //Open the thread (call the Run () method):Mt1.start (); //Create a new 21st thread:MyThread mt2=NewMyThread (); //Open the thread (call the Run () method):Mt2.start ();  for(inti=0;i<1000;++i) {System.out.println ("Main ..." +i); } System.out.println ("The program is over!" "); //View Main method thread name:System.out.println (Thread.CurrentThread (). GetName ()); }} PackageCom.oracle.duoxiancheng; Public classMyThreadextendsThread { Public voidrun () {System.out.println (Super. GetName ()); //rewrite the Run method, put the concurrency execution code inside, the Run method does not require the programmer to call, the thread object's. Start () method:         for(intj=0;j<1000;++j) {System.out.println ("Run ..." +j); }    }}

Create thread mode-Implement Runnable interface:

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

Benefit: Leave the task body (The Run () method in runnable) with the Create thread and the open thread (thread and Start () method)!

How to construct the thread class:

You can pass in a Runnable object, and a thread name!

Steps to create a thread:

1. Define class implementation 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!

The benefits of creating an open thread are achieved through the runnable and thread methods:

① implements the Runnable interface, avoids inheriting the single-inheritance limitation of the thread Class! Overwrite the Run method in the Runnable interface to define the thread task code in the Run Method!

② is more consistent with object-oriented thinking, which realizes the decoupling of thread task and thread Object!

The timed_waiting below should be waiting, where wait () and notify () belong to the object class!

Example code:

 PackageCom.oracle.duoxiancheng; Public classDemo01 { Public Static voidMain (string[] args) {//Thread new threads, and the main method are threads, the main method is the main thread, in memory to enjoy the independent stack space://Create a new first thread, set the thread name method ②,mythread overrides the thread's construction method:MyThread mt1=NewMyThread ("Zhuge Liang")); //Open the thread (call the Run () method):Mt1.start (); //Create a new 21st thread:MyThread mt2=NewMyThread (); //To set the thread name method ①:Mt2.setname ("Cai Wenji"); //Open the thread (call the Run () method):Mt2.start (); /*for (int i=0;i<1000;++i) {System.out.println ("main ..." +i); }*/System.out.println ("The program is over!" "); //View Main method thread name:System.out.println (Thread.CurrentThread (). GetName ()); }} PackageCom.oracle.duoxiancheng; Public classMyThreadextendsThread { PublicMyThread (String getName) {Super(GetName); }     PublicMyThread () {} Public voidrun () {System.out.println (Super. GetName ()); //rewrite the Run method, put the concurrency execution code inside, the Run method does not require the programmer to call, the thread object's. Start () method:        /*for (int j=0;j<1000;++j) {System.out.println ("Run ..." +j); }*/the thread is opened through the Runnable interface and the thread object: PackageCom.oracle.duoxiancheng; Public classDemo02 { Public Static voidMain (string[] args)throwsinterruptedexception {//runnable to write a class task:Myrunnable mr=Newmyrunnable (); //Thread is responsible for creating threads and opening threadsThread th1=NewThread (MR);        Th1.start ();  for(inti=0;i<50;++i) {            //sleep can awake itself:Thread.Sleep (5000); System.out.println ("Main ..." +i); }    }} PackageCom.oracle.duoxiancheng; Public classMyrunnableImplementsRunnable { Public voidrun () { for(inti=0;i<50;++i) {            Try{Thread.Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("This is inside the run () method ..." +i); }}} The anonymous object created and opened the thread: PackageCom.oracle.duoxiancheng; Public classDemo03 { Public Static voidMain (string[] args) {//anonymous inner class, the following new thread is a subclass of thread, except that it has no Name:        NewThread () { Public voidrun () { for(inti=0;i<50;++i) {System.out.println ("Run ..." +i);                }}}.start (); //Anonymous inner class, anonymous the new Thread object contains an anonymous inner class (subclass of Runnable):        NewThread (NewRunnable () { Public voidrun () { for(inti=0;i<50;++i) {System.out.println ("Run ..." +i);                }}). Start (); //The anonymous inner class, new Runnable () {} section is a subclass of runable, and the preceding Runnable ra= is polymorphic, passing in the constructor of the thread subclass object:Runnable ra=NewRunnable () { Public voidrun () { for(inti=0;i<50;++i) {System.out.println ("Run ..." +i);        }            }        }; Thread Ta=NewThread (RA); }}

2018-08-25 Multithreading thread Class +runnable interface + 6 states of 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.