Black Horse Programmer--java Foundation-multithreading

Source: Internet
Author: User

----------- Android Training , Java Training , Java Learning Technology blog, look forward to communicating with you! ------------

1, the understanding of threading

Process: Each independently executed program becomes a process.

Thread: A thread is an execution path inside a process.

Multithreading: There are multiple execution paths in a process at the same time.

The differences between threads and processes are as follows:

(1) Each process has a separate code and data space (process context), and the switching overhead between processes is significant.

(2) Multiple threads within the same process share the same code and data space, each thread has a separate run stack and a line order counter, and the switching overhead between threads is small.

2, thread creation, and startup

There are two ways to implement thread creation:

(1) Implement Runnable interface

(2) Inherit the Thread class

Startup method: method of invoking the Thread instance start()

Example:Firstthreadtest.java

/** Create and start multiple threads */public class Firstthreadtest {public static void main (string[] args) {System.out.println ("Main thread start Execution"); Thread thread1 = new Thread (new Myrunner ());//Start First thread thread1.start (); System.out.println ("Start a new Thread (THREAD1) ..."); Thread thread2 = new Mytread ();//Start a second thread thread2.start (); System.out.println ("Start a new Thread (thread2) ..."); System.out.println ("Main thread execution Complete");}}

  

/** implements self-java.lang.Runnable to create a class that intends to execute with threads */public class Myrunner implements Runnable {public void run () {//code to execute in thread for (int i = 0; i <; i++) {System.out.println ("Myrunner:" + i);}}}

  

Execution Result:

The main thread starts executing a new thread (THREAD1) ... Myrunner:0myrunner:1myrunner:2myrunner:3 Start a new thread (THREAD2) ... Main thread execution Complete myrunner:4myrunner:5myrunner:6myrunner:7mythread:0myrunner:8......mythread:94mythread:95mythread : 96mythread:97mythread:98mythread:99

  

Two child threads are created in the main thread, and the two sub-threads are executed alternately, which is a multithreaded program.

3, the life cycle of the thread:

When an instance (object) of the thread class is created, the thread enters a new state (not started).
For example:thread t1=new thread ();

Ready (runnable)
The thread has been started and is waiting to be allocated to the CPU time slice, which means that the thread is waiting in the ready queue to get CPU resources. For example:T1.start ();

Run (running)
The thread obtains the CPU resources that are executing the task (therun () method), at which point the CPU is automatically discarded by the thread A resource or a higher-priority thread enters, and the thread will run until the end.

Death (dead)
When a thread executes or is killed by another thread, the thread goes into a dead state, and the thread is no longer ready to wait for execution.

Natural termination: terminates after running the Run () method normally

Abort: Call the Stop () method to let a thread terminate the run

Clogging (blocked)
For some reason, the running thread is getting out of the CPU and pausing its own execution, which goes into a blocked state.

Sleeping: Use the sleep (Long T) method to put the thread into sleep mode. A sleeping thread can go into a ready state at the specified time.

Waiting: Call the wait () method. (Call motify () method back to ready state)

Blocked by another thread: Call the suspend () method. (Call resume () method Recovery)

Thread Sleep Example:threadsleeptest

/** Thread Sleep Example */public class Threadsleeptest {public static void main (string[] args) {System.out.println ("Main thread start Execution"); Thread thread1 = new Thread (new Sleeprunner ()); Thread1.start (); System.out.println ("Start a new Thread (THREAD1) ..."); Thread thread2 = new Thread (new Normalrunner ()); Thread2.start (); System.out.println ("Start a new Thread (thread2) ..."); System.out.println ("Main thread execution Complete");}} Class Sleeprunner implements Runnable{public void Run () {try {Thread.Sleep];  Thread sleep 100 milliseconds} catch (Interruptedexception e) {e.printstacktrace ()}//code to execute in the thread for (int i = 0; i <; i++) {SYSTEM.O Ut.println ("Sleeprunner:" + i);}}} Class Normalrunner implements Runnable{public void Run () {//code to execute in thread for (int i = 0; i <; i++) {System.out.printl N ("Normalrunner:" + i);}}}

  

Execution Result:

......... Normalrunner:96normalrunner:97normalrunner:98normalrunner:99sleeprunner:0sleeprunner:1sleeprunner:2sleeprunner : 3sleeprunner:4sleeprunner:5 .....

  

When the turn is sleeprunner , make it hibernate, perform the normalrunnerfirst, and so on when the sleeprunner sleep ends, Normarunner has been executed.

Thread Concession Example:threadyieldtest

/** Thread Concession Example */public class Threadyieldtest {public static void main (string[] args) {//Gets the name of the current thread        System.out.println (Th Read.currentthread (). GetName ());        Thread thread1 = new Thread (new Yieldthread ());        Thread1.start ();        Thread thread2 = new Thread (new Yieldthread ());        Thread2.start ();    }} Class Yieldthread implements runnable{public    void Run () {for        (int i = 0; i <; i++) {            System.out.println (Thread.CurrentThread (). GetName () + ":" + i);            if (i% = = 0) {    //When I can be divisible by 10, the current thread withdraws to the other thread            Thread.yield ();//thread concession method            }    }}}

  

Execution Result:

thread-1:96thread-1:97thread-1:98thread-1:99thread-0:76thread-0:77thread-0:78thread-0:79

  

Every time the condition is reached, the thread will make a concession.

Example of thread join:threadjointest

/** Thread Merge Operation */public class Threadjointest {public static void main (string[] args) {        thread thread1 = new Thread (new My Thread3 ());        Thread1.start ();        The main thread executes a for loop for        (int i = 1; i <=; i++) {            System.out.println (Thread.CurrentThread (). GetName () + ":" + i); 
   if (i = =) {                try {                thread1.join ();    The handle thread is added to the main thread to execute                } catch (Interruptedexception e) {    e.printstacktrace ();}        }}}    Class MyThread3 implements runnable{public    void Run () {for        (int i = 1; i <=; i++) {            System.out.prin TLN (Thread.CurrentThread (). GetName () + ":" + i);            try {            thread.sleep;              } catch (Interruptedexception e) {     e.printstacktrace ();}        }}    }

  

Execution results

Main:28main:29main:30thread-0:2thread-0:3thread-0:4thread-0:5thread-0:6

  

When the main thread arrives 30 o'clock to perform a concession operation, the child thread resumes execution after the execution of the thread

5. Methods commonly used in multi-threading

   1.sleep () method
Suspends execution of the currently executing thread for a specified period of time, but does not release"Lock Flag".
   sleep ()causes the current thread to enter a blocking state that does not execute for a specified period of time.
   2.wait () Method
On other threads that call the object'sNotifyorNotifyallcauses the current thread to wait before the method. The thread will release the one that it occupies ."Lock Flag"So that other threads have an opportunity to preempt the lock.
The current thread must have the current object lock.
   Waite ()and theNotify ()must be insynchronizedfunction orsynchronized Blockto make a call in the.
   3.yield Method
Pauses the currently executing thread object.
   yield ()just to get the current thread back to the executable state, so executeyield ()threads are likely to be executed immediately after they have entered the executable state.
   yield ()only threads with the same priority or higher priority have an opportunity to execute.
   4.join Method
Waits for the thread to terminate.
Wait for CallJointhe thread of the method ends, and then continues execution. such as:t.join ();//mainly used for waitingTThe thread runs the end, and if there is no such sentence,Mainwill be executed, resulting in unpredictable results.

  6. Summary:

    Multithreading is not the execution of multiple paths at the same time, but the system allocation of execution time, at the same moment or only one execution path, just because the CPU speed is very fast, so the feeling is at the same time, it is similar to the intersection of traffic lights, the same direction of the vehicle is divided into straight walking , turn left, turn right, the traffic light is our system, the vehicle is the code we execute.

Black Horse Programmer--java Foundation-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.