I genius official Free tutorial 39: Java Essentials thread

Source: Internet
Author: User

ThreadsThreads and Processes

Process: The smallest unit of the system's running program; a process with at least one thread
Thread: The smallest unit of execution of a program, and the thread-to-thread parallelism
A process has at least one thread, in Java this thread is called the main thread, created by the system, and runs the Main method. This way, a program with only one thread is called a single threaded procedure.
The main thread starts executing code from the program entrance main method, and executing code in any method is performed in a top-down order, which is difficult to achieve if there is only one main thread and the ability to listen to music online. Because the main thread must first download the music, after the download is complete, plays the music in the execution, this obviously does not satisfy today's people to listen to the music online demand. So now the program is multi-threaded, in terms of online listening to music this feature, you can create a thread in the main method responsible for downloading music, creating a thread responsible for playing music. This allows you to do other things while listening to music.


Creating Threads

Two ways to create a thread
1, implement Runnable interface: can also inherit other classes
2, inherit the thread class: easy to use

Mode one: <span style= "FONT-SIZE:14PX;" > Implement Runnable Interface </span>package thread;/** * Create myrunnable class and implement Runnable interface * @author Genius Federation-Yukun */public class Myrunnab Le implements Runnable {//must override the method in the Runnable interface, do not override a syntax error will occur//Runnable interface only declares a method run () @Overridepublic void Run () {// Thread Execution Code System.out.println ("Myrunnable-run");}}
Mode two: Package thread; /** * Create the MyThread class and inherit the thread interface * @author Genius Federation-Yukun */public class MyThread extends the thread {/* * Thread class also implements the Runnable interface and overrides the The Run method in the interface * so there is no syntax error if the Run method is not overridden here, but the thread created does not make sense anymore */@Overridepublic void Run () {//Thread execution code System.out.println (" Mythread-run ");}}
package thread;/** *  Creating test class test, testing the threads created in both of these ways   *  @author   Genius Alliance  -  Yukun  */public class test {public static void main (String[]  args)  {/***********  Way One  ************///  create an object of type myrunnable MRMYRUNNABLE&NBSP;MR  = new myrunnable ();//  creates a thread object T and passes Mr as a parameter to the thread object thread t = new  Thread (MR);/* *  Note: The startup thread calls the Start method in the thread class instead of calling the Run method; *  if the Run method is called directly, it will only represent the call of the Run method and will not start the thread;  *  call the Start method to start the thread T, and after the thread is started, the Run method in the object Mr is automatically called  */t.start ();/***********  mode two  ************///   Create an object of type MyThread mtmythread mt = new mythread ();//  because the Start method is declared in the thread class, The Mythread class inherits the thread class//  so the start method called with the object Mt here is a method inherited from the parent thread Mt.start ();}} Output result: Myrunnable-runmythread-run or Mythread-runmyrunnable-run 

Because multiple threads are executed in parallel, they run concurrently.
As far as the code is concerned, T.start () is executed first, and then Mt.start () is executed, but since the code here is very simple, in a very very short period of time, two of the field is started, and the thread is not executed immediately after it is started, waiting for the scheduler to choose which thread to execute. So the two threads that start here are executed first and cannot be determined. So the output order is also indeterminate.

The life cycle of a thread

New (initial state): After performing the new operation. The thread object has been created in memory at this time, but the thread has not started running
Can be run: After calling the start () method. At this point the thread has started, but it is not running (the execution of the thread is done by CPU), and the other is that the CPU is not being used, and that it is waiting for the scheduler of the system to pick up with other running threads, which thread to select, which is now using the CPU to execute the program, After a certain amount of time (the CPU's time slice), exit the CPU, go into a running state, and wait for the system scheduler to pick up with other threads.
Run: The CPU has been granted the right to use, is running
Blocking: After the sleep (int), yield (), join (), wait () methods are executed, the blocked thread is not selected by the scheduler. Access to the CPU is only possible after recovering from a blocking state to a functioning state
Death: After the end of the run or execution of the Stop (), Destroy () method, both methods are obsolete and deprecated, and the thread has completely stopped running, freeing up the resources that the thread occupies.


Scheduling Sleep Methods for threads

static void Sleep (int) method, it is recommended to use the class name thread call;
Role: Thread hibernation, which thread executes Thread.Sleep (), which thread will sleep (block), parameters of type int, the time (in milliseconds) that the thread sleeps, the end of time is automatically restored to a functioning state, and other threads wait for the scheduler to pick up
A word: Who executes, who sleeps.

Example: Package thread.sleep;/*** Create Sleepdemo class * For testing sleep methods * @author Genius Federation-Yukun */public class sleepdemo{public static void Main (string[] args) {System.out.println ("main thread is executing"); System.out.println ("Main thread hibernate start");//execute Thread.Sleep (); May produce an exception, use Try-catch statement to catch exception try {//This statement will be executed by the main thread, After execution the main thread sleeps 1000 milliseconds (1 seconds) thread.sleep (1000);} catch (Interruptedexception e) {//If the code in the try produces an exception, the program executes this output statement System.out.println ("an exception occurred during thread hibernation");} System.out.println ("Main thread Sleep End"); System.out.println ("Main thread recovery Execution");}} Output: The main thread is executing the main thread hibernate start "Here will Sleep (stop) 1 seconds, after 1 seconds continue to output the following" Main thread sleep end main thread resume execution


Yield method

static void Yield () method, recommended for use with the class name thread.
Function: The thread withdraws, which thread executes Thread.yield (); The statement, which thread will take the already obtained CPU right out, and enter the operational state, and other threads wait for the scheduler to choose;
sentence: Who executes, who gives in.

Instance:package thread.yield;/** *  creating Yielddemo class  *  concession execution for testing threads  *  @author   Genius Alliance  -  Yukun  */public  class  YieldDemo {public  static   void  main (String[]  args)  {//declares Threada and Threadb objects threada  ta =  new  threada (); THREADB&NBSP;&NBSP;TB&NBSP;=&NBSP;NEW&NBSP;&NBSP;THREADB ();//Start thread tata.start ();//Start thread Tbtb.start ();}} /** *  Create the Threada class and inherit the thread class  *  @author   Genius Federation  -  Yukun  */class   threada  extends  thread{//overriding the Run method in the parent class @overridepublic  void  run ()  {//Cycle 30 times for  (int  i  = 1;  i  <=  30;   i ++)  {/* *  An object of Threada class per cycle (in this case, TA) will give up the use of the CPU once, *  Execute to other threads (this example is the main thread and the Threadb object TB)  */thread.yield ();//Output a string, in order to see the execution frequency of thread ta in the result System.out.println (" threada-"&NBSP;&NBSP;+&NBSP;&Nbsp;i);}}} /** *  Create the Threadb class and inherit the thread class  *  @author   Genius Federation  -  Yukun  */class   threadb  extends  thread{//overriding the Run method in the parent class @overridepublic  void  run ()  {//Cycle 30 times for  (int  i  = 1;  i  <=  30;   i ++)  {//outputs a string in order to see the frequency of thread TB execution in the results System.out.println ("threadb--"   +   i);}}} Output: The output order is indeterminate; In most cases, the thread TB is executed first, the thread TA executes, and the thread TB executes more frequently than thread ta, but not absolute


Join method

void join ([int] [, int]), non-static method, can only be called with object.
Role: Thread queue jump; Assuming that threads A and B now execute b.join () in thread A, the statement that thread B will queue up to thread A and thread A will be blocked
A word: Who calls, who cuts, who executes, who blocks.
One can pass in an int type parameter, which represents the number of milliseconds to queue, and if the parameters of the two int type are passed in, the number of milliseconds (left) and nanosecond (right) of the queue is reached, and the queue thread and the blocked thread are returned to the operational state, waiting for the scheduler to pick

Instance:package thread.join;/** *  creating Joindemo class  *  concession execution for testing threads  *  @author   Genius Federation  -  Yukun  */public class JoinDemo {public  static  void   main (String[]  args)  {//creating Threada objects tathreada  ta = new   Threada ();//Start thread Tata.start ();}} /** *  Create the Threada class and inherit the thread class  *  @author   Genius Federation  -  Yukun  */class   threada  extends  thread{//overriding the Run method in the parent class @overridepublic  void  run ()  {//create threadb object TB; Thread TA executes this sentence threadb  tb = new  threadb () after running;//start thread TB After the thread TB starts, the thread TA and TB together wait for the scheduler to pick Tb.start ();//Loop 30 times for  (int  i  = 1;  i   <=  30;  i ++)  {/* *  when I equals 10 o'clock, execute Tb.join (); *  Make thread TB queue execution to thread TA front execution  *  thread ta blocked  */if  ( i == 10 )  {try {/*  *  Just jump in the queue once  *  when I is less than 10 o'clock, thread TA and TB co-wait for the scheduler's selection to execute  * i==10, when execution Tb.join (); *  executes, Thread ta is blocked, only thread tb; *  is executed until the thread TB is executed, TA will revert to the operational state  *  where TA is the performer of the Code, TB is the caller of the Code  */tb.join ();}  catch  (interruptedexception e)  {//The exception information in the output stack memory e.printstacktrace ();}} Output a string, in order to see in the results of the thread TA execution frequency System.out.println ("threada-"   +  i);}} /** *  Create the Threadb class and inherit the thread class  *  @author   Genius Federation  -  Yukun  */class   threadb  extends  thread{//overriding the Run method in the parent class @overridepublic  void  run ()  {//Cycle 30 times for  (int  i  = 1;  i  <=  30;   i ++)  {//outputs a string in order to see the frequency of thread TB execution in the results System.out.println ("threadb--"   +   i);}}} Because the order of the output is completely uncertain, the students here must test themselves


This article from the "Genius Union Education Official Blog" blog, reproduced please contact the author!

I genius official Free tutorial 39: Java Essentials thread

Related Article

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.