Java Phase III Learning (VI, multithreading)

Source: Internet
Author: User
Tags thread class

The difference between a process and a thread:

Process: refers to a running program that becomes a process when a program goes into memory run.

Threads: A thread is an execution unit of a process.

Summary: There will be at least one process after a program runs, and a process can have multiple threads .

Multithreading: Multithreading is a program that has multiple threads in progress .

The difference between a multithreaded and a single-threaded thread:

Single Threaded program: If more than one task is executed at the same time, you can execute the next one only after you finish the previous program.

Multithreaded program: If you have multiple programs that can be executed at the same time.

Second, the principle of program operation

1. Time-sharing scheduling : The CPU distributes the usage time evenly for threads, and all threads take turns using the CPU

2. Preemptive Scheduling: Prioritize the use of high -priority threads, if the same priority, it will randomly select a thread to use , Java is using preemptive scheduling. For example, when you open more than one software program at the same time, it will feel at the same time running, in fact, this time, the CPU is in many programs between the high-speed switch.

Conclusion: Multithreading does not increase the running rate of the program, but it can improve the efficiency of the operation, make the CPU more efficient and use more efficiently.

Third, the main thread

Package Com.oracle.demo01;public class Demo02 {//Main Thread    //procedures for executing from top to bottom    //Demo02 will start the JVM, run the Demo02,main, and look for the OS to go through the process when the compiler runs.    //for your CPU to have an execution path, run the Main method path has a name called "main", that is, the main thread    //Thread: Threadspublic staticvoidMain (string[] args) {//TODO auto-generated Method Stub         for(inti=0;i<1000000;i++) {System.out.println (i); } System.out.println ("This is the last word."); }}

When the above code is run, the "This is the last word" will be printed only after the number has been printed, because 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 in Java. main thread.

Four,thread Class (threading Class)

1 . Two ways to create a thread class:

1.1 Inheriting the thread class:

Step: 1. Create a class that inherits from the thread class

2. Overriding the Run method

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

4. Call the. Start () method, open the thread and let the thread execute, and tell the JVM to execute the Run method

Custom classes:

 Package com.oracle.Demo02; // creating threading methods by inheriting the thread class  Public class extends thread{    publicvoid  run () {        for (int i=0;i <100;i++) {            System.out.println ("This is the new thread" +i);     }}}

Test class:

 Packagecom.oracle.Demo02; Public classTest {//the JVM went to the OS and opened two threads.//for your CPU there are two paths, these two paths will be executed by the CPU, the CPU has its own choice of the right, so there will be random results,//You can also understand that two threads are robbing the CPU of resources (time)//OS: System program     Public Static voidMain (string[] args) {MyThread my=NewMyThread ();        My.start ();  for(inti=0;i<100;i++) {System.out.println ("This is the main thread" +i); }    }}

The difference between calling the run () method and invoking the start () method is that calling the Run method does not open a new thread, and calling start will open the new thread

1.2 Implementing the Runnable interface:

Step:1, define the 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.

Custom classes:

 Package com.oracle.Demo03; // Create a new thread by implementing the Runnable interface  Public class Implements runnable{    publicvoid  run () {        for (int i=0;i <10;i++) {            System.out.println (i);             }}}

Test class:

 Package com.oracle.Demo03; // to open a new thread by implementing the Runnable interface method  Public class Test4 {    publicstaticvoid  main (string[] args) {        Thread t= New Thread (new  runthread ());        T.start ();          for (int i=0;i<10;i++) {            System.out.println ("main" +i);     }}}

1.3 Multi-threaded memory plots

When multithreaded execution, in the stack memory, in fact, each execution thread has a piece of its own stack memory space. The stacking and stacking of methods.

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.

Summary: Each thread opens a new memory area in memory and does not queue behind the old thread

1.4 How to get the thread name :

1.thread.currentthread () Gets the current thread object

2.thread.currentthread (). GetName (); Gets the name of the current thread object

1.5 Anonymous internal classes for threads using

 Packagecom.oracle.Demo04;//thread anonymous inner class Public classDemo01 { Public Static voidMain (string[] args) {//Prerequisites for anonymous inner classes: must have inheritance or implementation//Format: New parent class or interface () {//the method to override;//}. Method (); //1. Inheriting anonymous objects of the thread class        NewThread () { Public voidrun () { for(inti=0;i<5;i++) {System.out.println ("Thread" +i);        }}}.start (); //2. Anonymous inner class for implementing the Runnable interfaceRunnable r=NewRunnable () { Public voidrun () { for(inti=0;i<5;i++) {System.out.println ("Runnable" +i);        }                            }                    }; Thread T=NewThread (R);    T.start (); }}

Java Phase III Learning (VI, 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.