Java multithreaded Programming-concepts and frequently used controls

Source: Internet
Author: User
Tags semaphore

Multithreading can satisfy the program ape to write a very efficient program to achieve the purpose of fully utilizing the CPU, due to the spare time of the CPU can be kept to a minimum. The key to effective use of multithreading is to understand that programs run concurrently rather than serially. For example: There are two subsystems in the program that need to run concurrently, this time need to use 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 (the process context).

There is a significant overhead involved in switching processes.

Process, is an "executing program".

A program is a static, lifeless entity that has the ability to become an active entity only if the processor gives the program life (operating system execution). We call it a process.

Other words. The process is an instance of the program being executed (an instance of a computer programs, which is being executed). For example, you perform a QQ. A process is started and QQ is executed again. It will start a process again.


  


Threads: in fact, the 60 's, the process is not only the basic unit of resource allocation. is also the basic unit of resource scheduling. However, with the development of computer technology, the process has appeared a lot of drawbacks, one is because the process is the resource owner. There is a large space-time overhead for creating, undoing, and switching, so you need to introduce a lightweight process. Second, because the symmetric multiprocessor (SMP) appears, it can satisfy multiple execution units, and multiple process parallel overhead is too high.

So in the 80 's, there was a basic unit-thread (Threads) that could be executed independently.

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


  


In a nutshell, it's. 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 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 to be wrapped by a thread class when it starts up Thread.Start ();// Call the Start method. Causes the thread to enter the ready state for (int i = 0; i < i++) {System.out.println ("" "Main" thread--> "+ i);}}}

Execution 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: Since Runner2 is already a thread class, there is no need to wrap it, call start directly to//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);}}}

Execution Result:



2.3 Summary

Although the same effect can be achieved in both ways, we generally do not implement multithreading in a way that inherits. As soon as you inherit the thread class, your class can no longer inherit other classes. And after the Runnable interface is implemented. You can also implement other interfaces or inherit other classes. This means that 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 "execution state".

That is, it is the thread that tells the operating system that I have everything I need to be dispatched, only that the thread will go into execution state after being dispatched.


four, the basic method of threading control

Here is the main introduction to sleep/join/yield/and the priority of threads. As for wait and notify/notifyall this pair of important methods will be in a later post. Thread synchronization issues are described in detail.



4.1 Sleep Method

Very easy non-common use, is the thread class static method:

Demo 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 such a way--rough//Mythread.stop ( );//More not--more rude} catch (Interruptedexception e) {return;}}}

There is a need to pay attention to the "terminating thread" approach, which mentions that both the interrupt () and the Stop () are in a more brutal way, that is, forced termination, generally not used.

Instead, a semaphore is defined in the thread class. The client then "tenderly" controls the termination of the thread by assigning the semaphore a value. 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, running the second thread in the order of the main threads , rather than concurrently.

Join (5000) represents the first 5 seconds of merging a second thread into the main thread, after 5 seconds. The second thread runs concurrently with the main threads.

Demo 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 run in the main sequence. Instead of running concurrently//Mythread2.join (5000);//First 5 seconds merge the second thread into the main thread, after 5 seconds. The second thread concurrently runs with the main 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");}}

Execution Result:




4.3 yield method

The static method of the thread class.

Pauses the currently running thread object and runs other threads. That's sharp sense. You have to pause, let others first run a little bit.

Demo 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);//Assuming I can be divisible by 10. Then let the CPU run 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 (only the main thread does not run complete) 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 a program. And the processor time should be allocated before the low-priority thread.

However, thread precedence does not guarantee the order in which threads are run and is dependent on the platform.

Demo 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. So it will be dispatched the opportunity is much larger than thread2 Thread1.start (); Thread2.start ();}}

Execution Result:




v. Summary

Process is the basic unit of system resource allocation, it is the execution demonstration sample of the program, can exist independently. The thread is the basic unit of CPU dispatch, it is the control flow inside a program, cannot exist independently. Must be attached to the process. A process consists of multiple threads, which are designed to obtain system resources, but are actually threads that operate these system resources.

By using multithreading, you can write very efficient programs. Just be aware that if you create too many threads, the efficiency of the program is actually reduced. Instead of ascending. Because of this, the switching overhead of the context is also very important. Assuming you create too many threads, the CPU spends more time switching the context than running the program!

Java multithreaded Programming-concepts and frequently used 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.