I genius official Free tutorial 39: Java Essentials thread

Source: Internet
Author: User

ThreadsThreads and Processesprocess: 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 Threadstwo 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 Myrunnable implements Runnable {//must override the method in the Runnable interface, do not override the 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 Run method in the interface * So if you don't rewrite the Run method here, there is no syntax error, but the thread created does not make sense. */@Overridepublic void Run () {//Thread execution code System.out.println (" Mythread-run ");}}
Package thread;/** * Create test class tests, test threads created in either of these ways  * @author Genius Federation-Yukun */public class Test {public static void main (string[] args) {/*********** mode one ************///creates an object of type myrunnable mrmyrunnable Mr = New myrunnable ();//Create a thread object T And passing Mr as a parameter to the thread object thread t = new thread (MR); * * Note: The startup thread invokes the Start method in the thread class instead of calling the Run method; * If you call the Run method directly, you will only represent the call of the Run method. Does not start the thread; * Call the Start method to start the thread T, and after the thread starts, it automatically calls the Run method in the object Mr */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 the 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 threadNew (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.


The scheduling of the thread sleep method 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 methodstatic void Yield () method, it is recommended to call with the class name thread.
Role: Thread concessions, which thread executes Thread.yield (), the statement, which thread will have already obtained the CPU use right out, and into the operational state, and other threads to wait for the scheduler to choose;
One sentence: Who executes, who withdraws.
Example: Package thread.yield;/** * Create Yielddemo class * For test thread concession execution * @author Genius Federation-Yukun */public  class  Yielddemo {  public static  void  main (string[]  args) {//declares Threada and Threadb objects Threada  ta = new  Threada (); THREADB  TB = new  threadb ();//Start thread tata.start ();//Start thread Tbtb.start ();}} /** * Create Threada class and inherit the Thread class * @author Genius Federation-Yukun */class Threada extends  thread{// Override the Run method in the parent class @overridepublic  void  Run () {//Loop 30 times for (int  i  = 1;  I  <=  ;  i + +) {/* * Each time the Threada class object (in this case, TA) is given the right to use the CPU, * to other threads (this example is the main thread and THREADB object TB) */thread.yield ();//Output a string, In order to see in the results the thread TA's execution frequency System.out.println ("threada-"  +  i);}}} /** * Create THREADB class and inherit the Thread class * @author Genius Federation-Yukun */class THREADB extends  thread{// Override the Run method in the parent class @overridepublic  void  Run () {//Loop 30 times for (int  i  = 1;  I  <=  ;  i + +) {//output a string, in order to see the execution frequency of the thread TB 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 use object invocation.
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
Example: Package thread.join;/** * Create Joindemo class * For test thread concession execution * @author Genius Federation-Yukun */public class Joindemo {public static void Main (string[] args) {//Create Threada object Tathreada ta = new Threada ();//Start thread Tata.start ();}} /** * Create Threada class and inherit the Thread class * @author Genius Federation-Yukun */class Threada extends thread{//overrides the Run method in the parent class @overridepublic void Run ( {//Create THREADB object TB; The thread TA runs and executes this sentence threadb TB = new threadb ();//start thread TB, thread TA and TB are waiting for the scheduler to pick Tb.start () when the threads are started, and/or  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 is blocked */if (i = =) {try {* * * * Only one queue at a time * at I less than 10 o'clock, thread ta and TB together wait When the scheduler is selected to execute * i==10, execute tb.join (); * After execution, thread ta is blocked, only executes thread TB; * Until the thread TB is executed, TA reverts to the operational state * where TA is the performer of the Code, TB is the caller of the Code */tb.join ();} catch (Interruptedexception e) {//output stack in memory exception information E.printstacktrace ();}} Output a string, in order to see the execution frequency of thread ta in the result System.out.println ("threada-" + i);}}} /** * Create THREADB class and inherit the Thread class * @author Genius Federation-Yukun */class THREADB extends thread{//overrides the Run method in the parent class @overridepublic void Run ( ) {//Loop 30 times for (int i = 1;  I <= 30; i + +) {//output a string, in order to see the execution frequency of the thread TB in the results System.out.println ("threadb--" + i);}}} Because the order of the output is completely uncertain, the students here must test themselves

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.