Java multithreaded Programming-concepts and common controls

Source: Internet
Author: User

Multithreading enables programmers to write very efficient programs to get the most out of the CPU, because the CPU's idle time is kept to a minimum. The key to effective use of multithreading is to understand that programs are executed concurrently rather than serially. For example, there are two subsystems in the program that need to be executed concurrently, which requires multithreaded programming. The running of a thread requires the use of the computer's memory resources and CPU.


I. The concept of process and threading

The concept of both, here only gives their own narrow understanding:

Process: A process is an entity of independent activity, which is the system basic unit of resource allocation . It can apply and own system resources. Each process has a separate code and data space (process context). There is a significant overhead involved in switching processes.

Process, is an "executing program". A program is a static, inanimate entity that can become an active entity, which we call a process, only if the processor gives the program life (the operating system executes it). In other words, a process is a running instance of a program (an instance of a computer programs, which is being executed). For example, you run a QQ, will start a process, run QQ again, will start a process.


  


Threads: In fact, in the 60 's, the process is not only the basic unit of resource allocation, but also the basic unit of resource dispatch. However, with the development of computer technology, the process has a lot of drawbacks, one is because the process is the resource owner, creating, undoing and switching there is a large space-time overhead, so need to introduce light process, second, because of symmetric multiprocessor (SMP) appear, can meet multiple operating units, and multiple processes parallel overhead too large. So in the 80 's, there was the basic unit-thread (Threads) that could run independently.

In other words, the thread is now the basic unit of resource (CPU) scheduling , which is a process of control within a program. A thread is a smaller unit within a process that does not consume system resources. Multiple threads within a process are designed to work together to handle one thing.


  


A simple summary is that the process is to allocate resources, and then the threads inside it use the resources to handle things. The process is a shell, and the actual officers are all threads. (for example, our main function acts as the main thread). Two more in-depth summary:http://wangzhipeng0713.blog.163.com/blog/static/1944751652015522359459/


second, thread creation and start-up
2.1 Way One: Threading class implements Runnable interface

To define a thread class:

/** * Define thread Class (implement Runnable interface) *  * @author Wangzhipeng *  */public class Runner1 implements Runnable {@Overridepublic vo ID run () {for (int i = 0; i < i++) {System.out.println ("New Thread runner1-->" + i);}}}

Test class:

public class TestThread1 {//1, Main method is main thread public static void main (string[] args) {//2, start second thread Runner1 runner1 = new Runner1 (); Thread thread = new Thread (runner1, "Zhipeng");//Note that the runner class implements the Runnable interface, which needs a thread class to wrap it up thread.start () when it starts up;// Call the Start method so that the thread enters the ready state for (int i = 0; i < i++) {System.out.println ("" "Main" thread--> "+ i);}}}

Operation Result:




2.2 Way Two: Thread class inherits the thread class and overrides its Run method

To define a thread class:

/** * Define thread Class (Inherit thread Class) *  * @author Wangzhipeng *  */public class Runner2 extends thread {@Overridepublic void run () {for (int i = 0; i < i++) {System.out.println ("New Thread runner1-->" + i);}}}

Test class:

public class TestThread2 {//Main method is main thread public static void main (string[] args) {///1, Thread class inherits the start notation of the thread class Runner2 Runner2 = New Runner2 (); Runner2.start ();//Note here: Because Runner2 is already a thread class, you do not need to wrap it, call start directly//2, The thread class implements the start notation of the Runnable interface (which needs to be wrapped with the thread Class)//thread thread = new Thread (runner1);//Thread.Start (); for (int i = 0; i < 100; i++) {System.out.println ("" "Main" thread--> "+ i);}}}

Operation Result:



2.3 Summary

Although the same effect can be achieved in both ways, we generally do not implement multi-threading in an inherited way, because once the thread class is inherited, your class can no longer inherit other classes. With the implementation of the Runnable interface, you can also implement other interfaces or inherit other classes. That is to say, interface-oriented programming is more flexible.


Third, the state transition of the thread


It is important to note that after the thread invokes the start () method, it enters the "ready state" instead of the "running state". That is, the thread tells the operating system that I have everything I need to be dispatched and that the thread is only going to run when it is dispatched.


four, the basic method of threading control

Here is a brief introduction to sleep/join/yield/and the priority of the thread, and the two important methods of wait and Notify/notifyall are described in detail in a later article, thread synchronization issues.



4.1 Sleep Method

Very simple, very common, is a static method of the thread class:

Sample Program

Thread class:

Import java.util.date;/** * Implement threading class by inheriting the thread class *  * @author Wangzhipeng *  */public class MyThread extends thread {pub LIC void Run () {/** * outputs the current date every second */while (true) {System.out.println ("---->" + new Date ()), try {sleep ()} catch (I Nterruptedexception e) {return;}}}

Sleep Test class:

public class Testinterrupt {public static void main (string[] argstrings) {MyThread MyThread = new MyThread (); Mythread.star t ();//start the second thread try {thread.sleep (5000);//5 seconds after the main thread terminates the second mythread.interrupt ();//generally do not terminate the thread in this way-compare rough//Mythread.stop () ;//Not much more--more rude} catch (Interruptedexception e) {return;}}}

Here you need to pay attention to the "terminate thread" approach, mentioned above interrupt () and stop () both methods are relatively rough way, that is, forced termination, generally not used. Instead, a semaphore is defined in the thread class, and then the client "gracefully" controls the termination of the thread by assigning a value to the semaphore. For example, a flag in the following thread class can be assigned a value of FALSE to terminate the thread.

public class MyThread extends Thread {Boolean flag = true;//defines the semaphore to control the termination of the thread public void run () {/** * Output the current date every second */while (f LAG) {System.out.println ("---->" + new Date ()), try {sleep (+),} catch (Interruptedexception e) {return;}}}

4.2 Join Method

Join () represents the merging of the second thread into the main thread, that is, the second thread is executed in the same order as the main course, rather than concurrently.

The join (5000) represents the first 5 seconds of merging the second thread into the main thread, and after 5 seconds, the second thread executes concurrently with the main threads.

Sample Program

Thread class:

/** * Define thread Class (Inherit thread Class) *  * @author Wangzhipeng *  */public class Mythread2 extends Thread {Mythread2 (String s) {sup ER (s);} /** * Output Every second when the name of the front thread */public void run () {for (int i = 0; i <; i++) {System.out.println ("I Am" + getName ()); try {T Hread.sleep (1000);} catch (Interruptedexception e) {return;}}}}

Join method Test class:

/** * Join Method Test *  * @author Wangzhipeng *  */public class Testjoin {public static void main (string[] args) {Mythread 2 mythread2 = new Mythread2 ("Zhpeng"), Mythread2.start ();//start a second thread try {mythread2.join ();//merge the second thread into the main thread, That is, the second thread is executed with the main thread sequence instead of concurrently//Mythread2.join (5000);//The second thread is merged into the main thread for the first 5 seconds, and after 5 seconds, the second thread executes concurrently with the master thread} catch (Interruptedexception E ) {e.printstacktrace ();} /** * Main thread: Loop output a sentence */for (int i = 0; i < i++) {System.out.println ("I am Main Thread");}}

Operation Result:




4.3 yield method

The static method of the thread class. Pauses the currently executing thread object and executes other threads. That is, sharp sense, you first pause, let others first execute the next.

Sample code

Thread class:

/** * Define thread Class (Inherit thread Class) *  * @author Wangzhipeng *  */public class Mythread3 extends Thread {public Mythread3 (String s) {super (s);} public void Run () {for (int i = 0; i < i++) {System.out.println (GetName () + ":  " + i);//If I can be divisible by 10, let the CPU execute the main thread , that is, the output of the sub-thread i is 0, 5, 10, 15, etc., the next output must be the main thread output (as long as the main thread is not executed) if (i% 5 = 0) {yield ();}}}

Yield method Test class:

/** * Yield method Test class *  * @author Wangzhipeng *  */public class Testyield {public static void main (string[] argstrings) {Mythread3 mythread3 = new Mythread3 ("------Zhipeng"); Mythread3.start ();//main thread for (int i = 0; i <; i++) {System.out . println ("-----mainthread" + i);}}

Output Result:




4.4 Thread Precedence Priority

Each Java thread has a priority, which helps the operating system determine the order in which the threads are dispatched. The Java priority is within the range of min_priority (1) and max_priority (10). By default, each thread will be assigned a priority of norm_priority (5).

A thread with a higher priority is more important to the program, and the processor time should be allocated before a low-priority thread. However, thread precedence does not guarantee the order in which threads are executed, and is very dependent on the platform.

Sample Program

Define two thread classes:

public class T1 implements Runnable {@Overridepublic void Run () {for (int i = 0; i <; i++) {System.out.println ("-- --------T1 ");}}

public class T2 implements Runnable {@Overridepublic void Run () {for (int i = 0; i <; i++) {System.out.println ("T2 ");}}}

Test class:

public class Testpriority {public static void main (string[] args) {Thread thread1 = new Thread (new T1 ()); Thread thread2 = new Thread (new T2 ()), thread1.setpriority (thread.norm_priority + 5),//priority for THREAD1 thread plus 5, This way it will be more likely to be dispatched than Thread2 Thread1.start (); Thread2.start ();}}

Operation Result:




v. Summary

A process is a basic unit of system resource allocation, which is a running example of a program that can exist independently. A thread is a basic unit of CPU scheduling, a process within a program that cannot exist independently and must be attached to a process. A process consists of multiple threads, which are designed to obtain system resources, but are actually threads that operate these system resources.

Through the use of multithreading, you can write a very efficient program. Note, however, that if you create too many threads, the efficiency of the program execution is actually reduced, not promoted. Because the context switching overhead is also important, if you create too many threads, the CPU spends more time switching the context than executing the program!

Java multithreaded Programming-concepts and common controls

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.