Multithreading (a) First knowledge multithreading

Source: Internet
Author: User
Tags thread class thread logic

I. Environment

Idea

Two. Why multithreading is used

As the saying goes: Crowds. Why not let a man pick up the firewood!!! Of course it's United!! But the best thing is to raise the efficiency .

So the same in the program, you can say a thread as a person, in order to speed up the efficiency of the process of multithreading.

three. What is a thread

Interview question: What is the difference between threads and processes

A: A thread is a way of running a program, and a process is a collection of threads

four. How to create Threads

Multithreaded execution We default to ignore the minimum error is executed at the same time, about who executes first to see who can first strong to the CPU execution right

4.1 Implementing the Thread class
 Public class extends Thread {    // override the thread type's Run method     @Override    public  void  Run () {        System.out.println ("Child thread runs-------");         // Logic code        for thread execution  for (int i=0;i<20;i++) {            System.out.println (getName ()+ "I:" +i);        }        System.out.println ("Thread End");}    }

To create a test class

 Public Static void Main (string[] args) {        threadtest threadtest=new threadtest ();   Create thread        threadtest.start ();   start thread for        (int i=0;i<20;i++) {            System.out.println ( Thread.CurrentThread (). GetName ()+ "I:" +i); // code that the main thread needs to run         }    }

Why not use the Thread.run () method to start Multithreading: As we create threads and normal new objects, using the Run method is equivalent to calling a method, rather than starting a multithreaded

4.2 Inheriting the Runnable interface
 Public class Implements Runnable {    // overriding the thread type's Run method public    void  run () {        System.out.println ("Child threads Run-------");         // Logic code        for thread execution  for (int i=0;i<20;i++) {            System.out.println (Thread.CurrentThread (). GetName ()+ "I:" + i);        }        System.out.println ("Thread End");}    }

To create a test class

 Public Static void Main (string[] args) {        threadtest threadtest=new threadtest ();   Create thread        thread=new Threads (threadtest);        Thread.Start (); // Start thread         for (int i=0;i<20;i++) {            System.out.println (Thread.CurrentThread (). GetName () + "I:" +i);   code that the main thread needs to run         }    }

Comparing this with the previous one, you can see that the two ways to create a thread are different

Interview question: Usually create thread is to use inherit thred class good or implement Runnable interface good

A: The implementation of the Runnable interface is good, because Java only supports single inheritance, but supports multiple implementations

4.3 Creating multithreading using anonymous inner classes
  Public Static voidMain (string[] args) {thread thread=NewThread (NewRunnable () {//Anonymous Inner class             Public voidRun () {//Business Logic Code                 for(inti=0;i<20;i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "Child thread I:" +i);        }            }        });        Thread.Start ();  for(inti=0;i<20;i++) {//main thread Logic code placeSystem.out.println (Thread.CurrentThread (). GetName () + "I:" +i); }    }
4.4 Multi-Threading Common API

Common Threads API Methods

Start ()

Start thread

CurrentThread ()

Gets the current thread object

GetID ()

Gets the current thread ID thread- number This number starts from 0

GetName ()

Gets the current thread name

Sleep (long Mill)

Dormant threads

Stop()

Stop the thread,

Common thread constructs function

Thread()

Assigning a new Thread Object

Thread(String name)

Assigns a new Thread object with the specified name as its name .

Thread(runable R)

Assigning a new Thread Object

Thread(runable R, String name)

Assigning a new Thread Object

Five. Mutual conversion of several states of multithreading

5.1 New status

when using New operator when creating a thread, for example New Thread (R) , the thread has not started running, and the thread is in the new state. When a thread is in a new state, the program has not started running code in the thread

5.2 Ready State

a newly created thread does not automatically start running, and the thread's start () method must be called to execute the thread . When the thread object calls the start () method, the thread is started,thestart () method creates the system resource running on the thread, and the dispatch thread runs run () method. When the start () method returns, the thread is in the ready state.

a thread in the ready state does not necessarily run immediately Run () method, the thread must also compete with other threads CPU time, only to get CPU time before the thread can run. Because in a single CPU computer system, it is not possible to run multiple threads at the same time, only one thread is running at a time. Therefore, there may be multiple threads in the ready state at this time. Multiple threads that are in a ready state are dispatched by the thread scheduler (threadsScheduler) of the Java runtime system .

5.3 Operating Status

when the thread gets after CPU time, it goes into a running state and really starts executing the run () method .

5.4 Blocking status

a thread may enter a blocking state for various reasons during the run :
1> thread goes to sleep by calling the Sleep method;
The 2> thread invokes an operation that is blocked on I/O , that is, the operation does not return to its caller until the input-output operation is complete;
the 3> thread attempts to get a lock that is being held by another thread;
4> thread is waiting for a trigger condition;

5.5 Death Status

There are two causes of thread death:
1) The Run method normally exits and dies naturally,
2) An uncaught exception terminates the run method and causes the thread to sudden death.
To determine whether a thread is currently alive (or is either operational or blocked), you need to use isAlive method. This method returns true if it is operational or blocked, or false If the thread is still in the new state and is not operational, or the thread is dead .

Six. The role of the Join () method

The join () method that calls that thread is the one that needs to execute the current thread when that thread finishes executing

For example:

  Public Static voidMain (string[] args) {FinalThread thread1=NewThread (NewRunnable () {//Anonymous Inner class             Public voidRun () {//Business Logic Code                 for(inti=0;i<20;i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "Child thread I:" +i);        }            }        }); Thread thread2=NewThread (NewRunnable () {//Anonymous Inner class             Public voidRun () {//Business Logic Code                Try{thread1.join (); } Catch(interruptedexception e) {e.printstacktrace (); }                 for(inti=0;i<20;i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "Child thread I:" +i);        }            }        });        Thread2.start ();    Thread1.start (); }

Result: no Thread1.join ()

Join Thread1.join ()

Multithreading (a) First knowledge 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.