in a multitasking system, each independently executed program is called a process, which is an "ongoing program." The operating system we are using is generally multitasking, which is the ability to execute multiple applications at the same time, where the operating system is responsible for allocating and managing resources for devices such as CPUs, although these devices can only do one thing at a time, but alternately execute multiple programs at very small intervals. You can give people the feeling of executing multiple programs at the same time.
A process can also contain one or more threads, a thread is a program inside the execution thread, if you want to implement multiple pieces of code in a program to run alternately, you need to produce multiple threads, and specify the code snippet to run on each thread, which is multithreaded.
One, define the thread1, extended Java.lang.Thread class. There is a run () method in this class, and you should be aware of its usage:
public void run ()
-
If the thread is constructed using a stand-alone
Runnable running object, the method of the object is called,
Runnable
run Otherwise the method does nothing and returns.
-
Thread Subclasses should override this method.
2, realize java.lang.Runnable interface. voidRun()
-
Runnable When you create a thread with an object that implements an interface, starting the thread causes the method of the object to be called in a thread that executes independently
run .
-
run The general contract for a method is that it may perform any required operations.
second, instantiate the thread1, if the extension of the Java.lang.Thread class thread, then the direct new can. 2, if the implementation of the Java.lang.Runnable interface class, then use the thread construction method: Thread (Runnable target)
Thread (Runnable target, String name)
Thread (threadgroup group, Runnable target)
Thread (threadgroup group, Runnable Target, String name)
Thread (threadgroup group, Runnable Target, String name, long stackSize)third, start the threadCall the Start () method on the thread object of the thread, not run () or any other method. Before the start () method is called: The thread is in the new state, the new state refers to a thread object, but there is no real thread. After the start () method is called: a complex set of things starts a new execution thread (with a new call stack), the thread is moved from new state to the operational state, and the target run () method runs when the thread gets an opportunity to execute. Note: For Java, the run () method has nothing special. Like the main () method, it is just a new thread that knows the method name (and signature) of the call. Therefore, it is legal to raise the Run method on runnable or thread. But does not start a new thread.
In Java to implement multi-threading, there are two ways, one is to continue the thread class, and the other is to implement the Runable interface.
For classes that directly inherit the thread, the code's approximate framework is:
Class Name extends thread{Method 1; Method 2; ... public void run () {//other code ...} property 1; property 2; ... }
Example:
/** * @author Rollen-holt inherit the thread class, call the Run method directly * */class Hello extends Thread {public hello () { } Public Hello (String name) { this.name = name; } public void Run () {for (int i = 0; i < 5; i++) { System.out.println (name + "Run " + i); } } Public static void Main (string[] args) { Hello h1=new hello ("A"); Hello h2=new Hello ("B"); H1.run (); H2.run (); } private String name; }
" Run Results":
A run 0
A Run 1
A Run 2
A Run 3
A run 4
B Run 0
B Run 1
B Run 2
B Run 3
B Run 4
We will find that these are executed sequentially, stating that our invocation method is not correct and that the start () method should be called.
When we change the main function above to the following:
<span style= "FONT-SIZE:14PX;" >public static void Main (string[] args) { Hello h1=new hello ("A"); Hello h2=new Hello ("B"); H1.start (); H2.start (); } </span>
Then run the program, the output of the possible results are as follows:
A run 0
B Run 0
B Run 1
B Run 2
B Run 3
B Run 4
A Run 1
A Run 2
A Run 3
A run 4
Because of the need to use the CPU resources, so every time the results of the operation is basically different, hehe.
Note: Although we are calling the start () method here, it is actually called the body of the run () method.
So: Why can't we just call the run () method?
My understanding is that the operation of the thread requires the support of the local operating system.
If you look at the source of the start, you will find:
Public synchronized void Start () { /** * This method was not invoked for the main method thread or "system" * g Roup threads Created/set up by the VM. Any of the new functionality added * to this method in the future May has to also is added to the VM. * * A Zero status value corresponds to state "NEW". * /if (threadstatus! = 0 | | this = me) throw new Illegalthreadstateexception (); Group.add (this); Start0 (); if (stopbeforestart) { stop0 (throwablefromstop); }} private native void Start0 ();
Notice that I use the red bold statement, which indicates that start0 () is called here. And this method uses the native keyword, the secondary keyword represents a function that invokes the local operating system. Because the implementation of multithreading requires the support of the local operating system.
However, the Start method repeats the call and the java.lang.IllegalThreadStateException exception occurs.
By implementing the Runnable interface:
Class Name implements runnable{Method 1; Method 2; ... public void run () {//other code ...} property 1; property 2; ... }
Example:
/** * @author rollen-holt Implementation Runnable Interface * */class Hello implements Runnable {public hello () { } Public Hello (String name) { this.name = name; } public void Run () {for (int i = 0; i < 5; i++) { System.out.println (name + "Run " + i); } } Public static void Main (string[] args) { Hello h1=new hello ("Thread A"); Thread demo= new Thread (H1); Hello h2=new Hello ("thread B"); Thread Demo1=new thread (H2); Demo.start (); Demo1.start (); } private String name; }
"Possible run Results":
Thread A runs 0
Thread B runs 0
Thread B runs 1
Thread B runs 2
Thread B runs 3
Thread B runs 4
Thread A runs 1
Thread A runs 2
Thread A runs 3
Thread A runs 4
About choosing to inherit the thread or implement the Runnable interface?
In fact, thread is also implemented Runnable interface :
Class Thread implements Runnable { //... public void run () { if (target! = null) { target.run ();}} }
The Run method in thread actually calls the run method of the Runnable interface. Do not know everyone found that the thread and runnable have implemented the Run method, this mode of operation is actually proxy mode. About the proxy mode, I have written a small example hehe, if you are interested, you can look at: http://www.cnblogs.com/rollenholt/archive/2011/08/18/2144847.html
The difference between thread and runnable:
If a class inherits the thread, it is not suitable for resource sharing. However, if the Runable interface is implemented, it is easy to realize the resource sharing.
/** * @author Rollen-holt inherits the thread class, cannot share resources * */class Hello extends Thread {public void run () {for (int i = 0; I < 7; i++) { if (Count > 0) { System.out.println ("count=" + count--); }}} public static void Main (string[] args) { Hello H1 = new Hello (); Hello h2 = new Hello (); Hello h3 = new Hello (); H1.start (); H2.start (); H3.start (); } private int count = 5; }
"Run Results":
Count= 5
Count= 4
Count= 3
Count= 2
Count= 1
Count= 5
Count= 4
Count= 3
Count= 2
Count= 1
Count= 5
Count= 4
Count= 3
Count= 2
Count= 1
As you can imagine, if this is a ticket-buying system, if count represents the number of tickets, the description does not share the resources.
Let's switch to Runnable interface:
/** * @author Rollen-holt inherits the thread class, cannot share resources * */class Hello implements Runnable {public void run () { int i = 0; I < 7; i++) { if (Count > 0) { System.out.println ("count=" + count--); }}} public static void Main (string[] args) { Hello he=new hello (); New Thread (He). Start (); } private int count = 5; }
"Run Results":
Count= 5
Count= 4
Count= 3
Count= 2
Count= 1
Let's summarize:
The benefits of implementing the Runnable interface are more than inheriting the thread class:
1): Suitable for multiple threads of the same program code to process the same resource
2): Can avoid the restriction of single inheritance in Java
3): Increase the robustness of the program, the code can be shared by multiple threads, code and data Independent.
/** * @author Rollen-holt * Get the name of the thread * */class Hello implements Runnable {public void run () {for (int i = 0; I < 3; i++) { System.out.println (Thread.CurrentThread (). GetName ())} } public static void Main (string[] args) { Hello he = new Hello (); New Thread (He, "A"). Start (); New Thread (He, "B"). Start (); New Thread (He). Start (); } }
"Run Results":
A
A
A
B
B
B
Thread-0
Thread-0
Thread-0
Description if we do not specify a name, the system automatically provides the name.
Remind everyone: Main method is actually a thread. In Java So the threads are all started at the same time, as to when, which first executes, fully see who first get the CPU resources.
in the Java start at least every time the program runs 2 a thread. One is the main thread and one is the garbage collection thread. Because every time a class is executed with a Java command, a JVM is actually started, and each JVM internship starts a process in the operating system.
Determines whether a thread is started
/** * @author rollen-holt determine if thread starts * */class Hello implements Runnable {public void run () {for (int i = 0; I < 3; i++) { System.out.println (Thread.CurrentThread (). GetName ())} } public static void Main (string[] args) { Hello he = new Hello (); Thread demo = new Thread (he); SYSTEM.OUT.PRINTLN ("---before thread start" + demo.isalive ()); Demo.start (); SYSTEM.OUT.PRINTLN ("---after thread start" + demo.isalive ()); } }
"Run Results"
---before thread starts "false
---After the thread is started "true
Thread-0
Thread-0
Thread-0
The main thread may also end before the child thread ends. And the child threads are not affected, and will not end because of the end of the main thread.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Multithreading in Java