Java Note 5. Multithreading

Source: Internet
Author: User

Java Note 5. Multithreading
Multithreading in Java (1)1. Understand threads 1. process, thread, and Multithreading
1. Process: In a multitasking system, each independently executed Program (or an ongoing program) is called a process. 2. Thread: A process can contain one or more threads. A thread is an execution clue (part of code) within a program ). 3. multithreading: If you want to implement multi-segment code in a program to run alternately at the same time, you need to generate multiple threads and specify the program code to run on each thread, that is, multithreading. Note: In a single thread, the execution of program code is executed sequentially in the order of calls, and the running of program code at both ends cannot be executed at the same time. When our program starts to run, a thread is automatically generated. The main function mian runs on this thread. When no new thread is generated, the program is a single thread. Therefore, in this case, the program process is the main thread. 2. Thread class(1) constructor

Thread(): Creates a thread object.
Thread(Runnable target): Creates a thread object with Runnabke object parameters.
Thread(Runnable target, String name): Creates a thread object with Runnable object parameters.
Thread(String name): Creates a thread object and specifies the thread name.Allocates a newThreadObject.
(2) Main method: static Thread currentThread (): returns the Thread object long getId (): returns the Thread ID String getName (): returns the thread name int getPriority (): returns the thread's priority void interrupt (): interrupts the thread boolean isAlive (): determines whether the thread is in the active state boolean isDaemon (): determine whether the thread is a daemon void join (): Merge thread
Void join (long millis): Wait for the thread millis millisecond, and then separate it to the status before merging void run (): When the thread is running, run () of the Runnale object () method is called to execute the relevant code void setDaemon (boolean on): set this thread as the daemon void setName (String name ): set to change the thread name to name void setPriority (int newPriority): set to change the thread priority (MAX_PRIORITY/MIN_PRIORITY/NORM_PRIORITY) static void sleep (long millis ): this method changes the running thread into sleep state and releases the CPU control. After millis milliseconds, the thread is awakened again and the CPU control is again obtained void start (): after a thread is created, call this method to start the thread. Java Virtual Machine calls the thread's run method 3. runnable interface (1) Function :If we define a class to be executed through a thread, we can make the class inherit this Runnable interface and implement a run () method without parameters in the class. Classes inherited from the Runnable interface do not need to inherit the Thread class. You only need to instantiate an object of the class and use it as the Thread object parameter to run custom class code in a Thread. (2) method void run (): when an object inherited from the Runnable interface is used to create a thread, to start this thread, the run method in the defined class will be executed in a separate thread.
2. Two ways to create a threadJava creates multithreading in two ways: Inheriting the Thread class and implementing the Runnable interface. 1. Use the Thread class to create a Thread (1) PrincipleJava threads use java. lang. the Thread class is controlled. The object of a Thread class represents a Thread and can only represent a Thread. Through the Thread class and the object defined by it, we can obtain the current thread object, set the thread priority, obtain the name of a thread, or control the thread to suspend for a period of time. (2) development ideasA. implement a class so that the class inherits from the Thread class; B. the run () method of this class is used to implement the tasks we want the thread to complete. c. instantiate an object of this class and call its start () method to start this thread. (3) source code example
// Main thread public class DemoThread {public static void main (String arg []) {TestThread Thread = new TestThread (); // create a thread subclass object thread. start (); // start this subthread while (true) {System. out. println (main thread is running .);}}} // class TestThread extends Thread {public void run () {while (true) {System. out. println (Thread. currentThread (). getName () + is running .);}}}
Analysis: by observing the program running status, we can see that the program has two threads (multiple threads) that run irregularly alternately. Effect:
Sublimation Note 1: 1. to implement multithreading, We must compile a subclass that inherits the Thread class, And the subclass must overwrite the run () method in the Thread class, in addition, compile the functional code we want to implement on the new thread in the run method of the subclass; 2. starting a new Thread does not directly call the run () method of the Thread subclass object. The second is to call the start () method of the Thread subclass object, the start method of the Thread class object will generate a new Thread and run the run method in the Thread class object on the Thread. 3. because the code segment of a thread is in the run method, after the run () method is executed, the corresponding thread ends, therefore, we can control the thread termination by controlling the loop conditions in the run method. 2. using the Runnable interface to create multithreading (1) principle when using the Thread (Runnale target) method to create a Thread object, you need to pass a class object that implements the Runnable interface for this method, in this way, the created Thread uses the run () method in the Class Object implementing the Runnable interface as its running code, rather than calling the run method in the Thread class. (2) development ideasA. implement a class that inherits from the Runnable interface and overwrites the run () method that implements the Runnable interface; B. instantiate an object of this class and use this object as a parameter to instantiate a Thread class object; c. call the start () method of the Thread class to start the subthread; (3) source code example
// Main thread public class RunnableTest {public static void main (String args []) {TestRunnable runnable = new TestRunnable (); // create a class object, this class inherits from the Runnable interface Thread thread = new Thread (runnable); // creates a thread Thread with Runnable object parameters. start (); // start this thread while (true) {System. out. println (main thread is running .);}}} // sub-Thread class TestRunnable implements Runnable {@ Override public void run () {while (true) {System. out. println (Thread. currentThread (). getName () + is running .);}}}
Effect:
3. Comparison and Analysis of Two multithreading MethodsThrough the above two examples, we know that both the inherited Thread class and the Runnable interface can implement multithreading, and we do not see any difference between the two. However, when we want to develop multiple threads to process the same resource (one resource can only correspond to one object), the method of inheriting the Thread class is a little powerless. For example, a program is used to simulate the railway ticket sales system, which enables the sale of 100 tickets for a certain train on a certain day at four ticket sites. A ticket point is represented by a thread. (1) inherit the multi-Thread of the Thread class
// Main thread public class SaleTickets {public static void main (String [] arg) {new Resource (). start (); // start thread 1 new Resource (). start (); // start thread 2 new Resource (). start (); // start thread 3 new Resource (). start (); // start Thread 4} // unique Resource class Resource extends Thread {private int tickets = 100; // 100 tickets @ Override public void run () {// each time the thread runs the run method, the number of votes minus 1 while (tickets> 0) {System. out. println (Thread. currentThread (). getName () + is saling tickets + tickets --);}}}

Analysis: as a result, we know that the four threads created in the main thread each sell their own 100 tickets, rather than the same 100 tickets, that is to say, these threads are not processing the same resource! In fact, in the above program, four Resource objects are created, which means four resources are created. Each Resource object has 100 tickets, and each thread processes its own resources independently. Effect:
(2) inherit multiple threads of the Runnable Class Method
// Main thread public class SaleTickets {public static void main (String [] arg) {Resource r = new Resource (); // instantiate a Runnbale subclass object, represents a resource./* four sub-threads are created in sequence */new Thread (r ). start (); new Thread (r ). start (); new Thread (r ). start (); new Thread (r ). start () ;}// unique Resource class Resource implements Runnable {private int tickets = 100; // 100 tickets @ Override public void run () {// each time the thread runs the run method, the number of votes minus 1 while (tickets> 0) {System. out. println (Thread. currentThread (). getName () + is saling tickets + tickets --);}}}
Analysis: The above program meets the requirements of the simulated Railway Ticketing System. We can see from the above program that we have created only one Resource object Resource (this object contains the 100 tickets to be sold ). Then, we are creating four threads, each of which calls the run () method in the same Resource object. Therefore, these four threads access instances of variables (tickets) in the same object, this allows multiple threads to access the same resource. Effect:
Sublimation NOTE 2: What are the advantages of implementing the Runnable interface over inheriting the Thread class? 1. the Runnable interface is suitable for multiple threads with the same program code to process the same resource, effectively separating the virtual CPU (thread) from the program code and data, it better reflects the object-oriented design philosophy; 2. this avoids the limitations caused by Java's single inheritance feature. We often encounter this situation, that is, when we want to put sub-classes that have inherited a certain type into multithreading, because a class cannot have two parent classes at the same time, therefore, we cannot inherit the Thread class, so this class can only implement the Runnanle interface. 3. Implementing the Runnable interface is conducive to program robustness. The code can be shared by multiple threads, and the code and data are independent. When multiple first executed codes come from instances of the same class, they share the same code. Multiple Threads can operate on the same data, regardless of their code. When shared access to the same objects, that is, they share the same data. When a thread is constructed, the required code and data are passed through an object as the real parameter of the constructor. This object is an instance of the class that implements the Runnable interface.
3. daemon (background) process and federated Process 1. Background Process (1) Overview:In the example of the ticket system above, after we create and start a new thread in the main method, the main method ends and the main thread ends. However, we know that the entire Java program (process) does not end as long as there is a front-end thread running during the Java program running, the host process of the sub-thread becomes an empty process. Of course, if we set the new thread to a background process, if only the background process is running in a process, the process will end with the end of the main method. Set a process as a background process: Thread thread = new Thread (runnable); thread. setDaemon (true); // set the sub-process as the daemon thread. start (); (2) source code example
// Main thread public class RunnableTest {public static void main (String [] args) {int I = 10; TestRunnable runnable = new TestRunnable (); // create a class object, this class inherits from the Runnable interface Thread thread = new Thread (runnable); // creates a thread Thread with Runnable object parameters. setDaemon (true); thread. start (); // start the thread while (-- I> 0) {System. out. println (main thread is running .);}}} // sub-Thread class TestRunnable implements Runnable {@ Override public void run () {while (true) {System. out. println (Thread. currentThread (). getName () + is running .);}}}

Demo:
2. federated threadThe so-called federated thread is when a thread calls join () [such as pp. join (), where pp is the thread object method, merge the threads corresponding to pp to call pp. in the thread of the join () statement. (1) method of Thread class: void join (): Merge Thread
Void join (long millis): After the thread merges millis in milliseconds, it is separated to the status void join (long millis, int nanos) before the merge ): example of source code for separating a thread from a millis millisecond nanos nanoseconds to a State before merging (2)
Public class joinThead {public static void main (String [] args) {testThread t = new testThread (); // create a Runnable subclass object Thread thread = new Thread (t ); // create a thread. start (); // start thread int I = 100; while (I> 0) {if (I = 50) {try {thread. join ();} catch (InterruptedException e) {e. printStackTrace () ;}} System. out. println (main thread: + I --) ;}} class testThread implements Runnable {private int I = 100; public void run () {while (I> 0) {I --; system. out. println (Thread. currentThread (). getName () +: + I );}}}

Result Analysis:
After observation, we can see that when the main thread's I decline = 50, the sub-thread and the main thread are merged. At this time, only the I in the sub-thread is being calculated, until the sub-thread run method code runs completely two threads and then separates them. Finally, the main thread continues to execute the subsequent code.

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.