J2SE Fast Advanced--java multithreading mechanism

Source: Internet
Author: User

When you learn threads in Java, you naturally associate the knowledge of the processor in the operating system that you learned earlier.

Definition

At the beginning of the article, let's talk about the concepts of programs, processes, and threads, and their relationships.

Program: A program is a static code, or an executable program.

Process: A process is a dynamic execution of a program that corresponds to a dynamic execution process from code loading to running to ending.

Threads: An execution unit that is smaller than a process, in which a process can produce multiple threads, that is, multiple branches. It is the smallest unit of program execution flow.

To see a small program:

public class Test {public static void main (string[] args) {fun1 ();} public static void Fun1 () {System.out.println (fun2 () +fun3 ());} public static String fun2 () {return "Hello";} public static String Fun3 () {return ' world! ';}}

its execution order is as follows, in the main method, from ① execution to ⑥ is a line, and there is no branch, this is a thread.


Implementation of Threads

When the JVM executes to the main method, a thread is started, called the main thread. If other threads are also created in the Main method, the JVM shifts between the main thread and other threads to ensure that each thread has the opportunity to use the CPU resources.

Threads in Java are implemented through the Java.lang.Thread class, and each thread object represents a new thread.


There are two methods of implementing threading in Java:

1. Inherit the thread class and rewrite its Run method (used to encapsulate the command to be executed by the entire thread) and call the Start method to start the thread.

For example, the following class T to implement a thread, the code is as follows:

public class Createthreadtest{public static void Main (string[] args) {T r=new t (); R.start ();   The thread of the T class begins execution for (int i=0;i<100;i++) {System.out.println ("The main thread is executing ~ ~ ~ ~" +i);}} Class T extends Thread{public void run () {//Override the Run method in the parent class for (int i=0;i<100;i++) {System.out.println ("The thread I created is executing ~ ~ ~ ~" + i);}}}
now, this small program has a total of two threads executing, one is the main thread, and the other is the T class created thread.

2. Implement Runnable interface

Another way is to enable the implementation of the thread class implementation runnable interface, the implementation of the Runnable interface is the only method run (), and then the instance of this class as the thread class constructor parameters, create the Thread object.

For example, the example above can also be written like this:

public class Createthreadtest {public static void main (string[] args) {T r=new t (); Thread t=new thread (r);    Create thread Object T.start ();    The thread of the T class starts for (int i=0;i<100;i++) {System.out.println ("main thread is executing ~ ~ ~ ~" +i);}} Class T implements Runnable {public void run () {for (int i=0;i<100;i++) {System.out.println ("The thread I created is executing ~ ~ ~ ~" +i);}}

The essence of both approaches is that you need to rewrite the Run method, which is ultimately started by the thread class's Start method.

tip : Because multiple inheritance is not supported in Java, when you implement a thread, you cannot inherit another class once you have inherited the thread class. However, Java supports the implementation of multiple interfaces, so it is recommended to adopt the second method, which is more flexible.


Multithreading

multithreading is primarily to accomplish multiple tasks synchronously , that is, executing multiple threads at the same time. Multithreading divides a process into multiple tasks, which work independently of one another

As we all know, most operating systems, such as Windows, Mac OS X, Unix, Linux and so on, are multi-threaded, but what we usually call multi-threading does not mean that the CPU will process multiple threads at the same time, and that each CPU will only process one thread at the same point, c1> is just too fast and processing time is so short that we can think of it as being able to handle multiple threads in the same time period. so it is only when your machine is "dual-core" or "multicore" that it is possible to realize multithreading in real sense.                                                                                             

Here is an example of multithreading:

Execution of two threads T1 and T2

public class ThreadTest {public static void main (string[] args) {thread t1=new thread (new T1 ()); Thread T2=new Thread (new T2 ()); T1.start (); T2.start ();}} Class T1 implements Runnable{public void Run () {for (int i=0;i<10;i++) {System.out.println ("Thread 1 is executing------" +i); if (i= =9) {System.out.println ("Thread 1 execution ended------" +i); Class T2 implements Runnable{public void Run () {for (int i=0;i<10;i++) {System.out.println ("Thread 2 is executing------" +i); if (i= =9) {System.out.println ("Thread 2 execution ended------" +i);
before you look at the results, make the most of your brain and think about what the results should look like.

Execution Result:

Is it different from what you predicted? If you do not add a thread, the original result should be the first 10 rows are thread 1 in the execution, thread 1 after the execution of thread 2 to start execution, thread scheduling algorithm so that each thread executes a wait state, and then to execute another thread.

Common methods in threading

If you have tried this example above, you will find that these two threads T1 and T2 who performed first, who executed, who executed for how long, etc. these are indeterminate and not controllable. Here are some of the methods that are commonly used in a thread.

★void yield () method

In one thread, if the yield () method is executed, the thread yields the CPU resources, pauses the currently executing thread object, and instead lets the CPU execute other threads with the same priority. Fully embodies the thread willing to humility spirit!

Example: I values from 0 to 99, each time the name of the output thread instance, when I is a multiple of 10, the yield method is executed.  

public class Testyield {public static void main (string[] args) {MyThread thread1=new MyThread ("Thread1"); MyThread thread2=new MyThread ("Thread2"); Thread1.start (); Thread2.start ();}} Class MyThread extends Thread{mythread (String name) {super (name);} public void Run () {(int i=0;i<100;i++) {System.out.println (GetName () + ":" +i); if (i%10==0) {yield ();}}}}
from the first few outputs in the results can be found, for thread1, whenever I is a multiple of 10, the process will yield, thread2 process execution; Thread2 is the same:

NOTE: The yield () method switches the currently running thread to a running state, but may not be effective because the thread that actually executes the yield method may also be checked again by the scheduler.

★void Sleep (Long Millis) method and void sleep (long millis,int Nanos)

Allows the thread to hibernate (pause execution) for a specified length of time, the unit of the parameter Millis is milliseconds, and the parameter Nanos is in nanoseconds. After the thread executes the sleep method, it goes into a blocking state, and after the specified time period, the thread enters the executable state and waits for the operating system to dispatch.

Example:       

Import java.util.*;p Ublic class Testsleep {public static void main (string[] args) {MyThread thread=new MyThread (); Thread.Start ();}} Class MyThread extends Thread{public void run () {while (true) {System.out.println ("= = =" +new Date () + "= = ="); Try{sleep ( 1000);} catch (Interruptedexception e) {return;}}}}
After reading the code you should guess the result, every second will output the current time, equivalent to a timer. This program has a total of two threads, the main thread (that is, the Main method) out of the execution thread thread there is no other task needs to execute, so here can be seen as only the thread is executed, if the example of the sleep method is removed, then the "Swish swish" Continuously output the current time (your CPU fan will also "swish swish" ~ ~ ~).

★void Join () method

It says that when a thread executes the yield method, it automatically gives up the CPU resources and transitions the state from the running state to the operational state. The join () method can be said to be exactly the same, and when a thread executes the Join method, it will continue to execute until the thread ends.

Or For example:

public class Testjoin {public      static void Main (string[] args) throws interruptedexception {          Thread t1 = new Threa D (New Threada ());          Thread t2 = new Thread (new threadb ());          T1.start ();          T1.join (); After the T1 thread starts executing, it will continue to execute until the T1 thread ends, otherwise the CPU          T2.start () is never conceded;          T2.join (); After the T2 thread starts executing, it will continue to execute until the T1 thread ends, otherwise never let go of the CPU      }  }class Threada implements Runnable {public       void run () {          for (int i=0;i<10;i++) {              System.out.println ("A thread is running ~ ~ ~" + i          )       ;   }}} Class THREADB implements Runnable {public   void run () {for          (int i=0;i<10;i++) {              System.out.println (" b Thread is running ~ ~ ~ + i);}       }   
first of all, if you join T1 and T2 two threads do not execute the join method when they are started, the execution time and order that the CPU assigns to them are not necessarily the same, such as left, and if T1 and T2 execute the Join method, they will execute as soon as they start executing, as right.


      

Why use multithreading

One last question, why use multithreading?

In the forum to see a Daniel metaphor: single-threaded is the boss from start to finish, another thread is the boss broke out a thing called a little brother to do, this little brother's entry will speed up the whole thing progress, but sometimes may do things to get in the way.


Of course, to understand the essence of multithreading more deeply, it is not enough to learn these theories, more importantly, in practice and projects to dig and think.


J2SE Fast Advanced--java multithreading mechanism

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.