I. Overview 1, the way of realization
In Java for a multithreaded implementation must have a thread of the main class, and the main class of this thread is often required to operate some resources, but for the main class of multi-threaded implementation is:
Inherit thread parent class
Inheriting from the Java thread class implements multi-threading, is also implementing its Run method, then declaring the instance, and invoking the instance's Start method to start the thread.
Implementing the Runnable Interface (callable interface)
It takes two steps to implement multithreading using the Runnable interface, first implementing the Runnable interface class, then declaring the thread instance, invoking the Start method of the thread instance, and starting execution.
2. Introduction to the main methods of Java thread class
instance method for thread:
Method definition |
Method description |
public void Start () |
The most commonly used method, as the name implies, starts the thread, that is, the run method that executes the thread |
public void Run () |
If the thread overrides the Run method, then executes the overridden method, otherwise the run method defined in the Runnable interface of the execution thread |
Public final void SetName (String) |
Set the name of the thread |
Public final void setpriority (int) |
Set the priority of the thread (range 1-10 contains 1, 10) |
Public final void Setdeamon (Boolean) |
Sets whether the thread is a background thread |
Public final void join (long) |
Calling the join method of the current thread in another thread causes the current thread to block until the other one finishes executing, or the parameter specifies the number of milliseconds |
public void Interrupt () |
Break Thread in |
Public Final Boolean isAlive () |
Whether the thread is alive, the thread is alive before it starts and ends |
Common static methods for the thread class:
Method definition |
Method description |
public static void Yield () |
A thread that has the same priority as the current running thread gets an execution opportunity, like sleep, but only gives the CPU the same priority thread |
public static void sleep (long) |
Time that the current thread sleeps for a specified millisecond |
public static Boolean Holdslock (Object x) |
Determines whether the current thread owns an object's lock |
public static Thread CurrentThread () |
Get current Thread instance |
public static void DumpStack () |
Prints the execution stack of the current thread, which is useful for debugging multithreaded threads |
Second, inherit the thread class
Java.lang.Thread, subclass inherits thread, then overwrite run method, thread Main method
class MyThread extends Thread { private String name; public MyThread (String name) { this . Name = name; } @Override public void Run () {
//
for (int i = 0; I < 10; I++ this . Name + "I:" + i); } }}
It is important to note that all threads are braided, and that there are multiple threads alternately executing over a certain period of time. Therefore, in order to achieve this goal, it is absolutely not possible to call the Run method directly, but instead call the Start method in the Thread object
New MyThread ("Thread A"); New MyThread ("Thread B"); New MyThread ("Thread C"); // Mt1.run () is now the method invocation order execution mt1.start (); Mt2.start (); Mt3.start ();
Thinking? Why does multi-threaded boot not run, but use the Start method? Source
Public synchronized voidstart () {if(Threadstatus! = 0) Throw NewIllegalthreadstateexception ();//Exception DescriptionGroup.add ( This); Booleanstarted =false; Try{start0 (); Started=true; } finally { Try { if(!started) {group.threadstartfailed ( This); } } Catch(Throwable ignore) {}}} Private native voidStart0 ();
View Code
Source Code Analysis:
1, throw new Illegalthreadstateexception (); Exception description
Is runtime exception, multiple startup will throw
2, Start0 ()
Invoking the native operating system functions of native
Since thread initiation requires the allocation of resources in the operating system, the start-up of a specific thread needs to be implemented differently depending on the operating system, and the JVM is equivalent to the implementation of the method according to the Start0 () method defined in the system, so that it can be implemented on a multi-threaded level start0 () The method name is the same, and different implementations are available on different operating systems.
Conclusion: Only the Start () method of the thread class is able to allocate the resources of the operating system, so the way to start multithreading is always to invoke the start of the thread class.
Third, realize runnable interface
In the design process, as few as possible to inherit the ordinary class, the single inheritance occurs. Try to implement an interface or abstract class.
Inheriting the thread class results in a single inheritance limitation, so it is now best to take advantage of an interface implementation.
Implemented using the Runnable interface. Structure of the Runnable interface:
@FunctionalInterface Public Interface Runnable { publicabstractvoid run (); abstract method for interface definition }
The code at this point uses a functional interface, which can be done using a lambda expression
1. General implementation
class MyThread2 implements Runnable { private String name; public MyThread2 (String name) { Span style= "color: #0000ff;" >this . Name = name; } @Override public void Run () {
//
for (int i = 0; I < 10; I++ this . Name + "I:" + i); } }}
If starting a multithreading can only rely on the start method in the thread class, previously inherited thread could be used, and now inherits the Runnable interface without this method.
To view the construction method in the Thread class: public Thread (Runnable target)
New MyThread2 ("Thread A"); New MyThread2 ("Thread B"); New MyThread2 ("Thread C"); New Thread (mt21). Start (); New Thread (mt22). Start (); New Thread (mt23). Start ();
2, Anonymous internal class implementation
String name = "Thread Object"; // previously must be added Finall, due to LAMDBA, can not be applied New Thread (new Runnable () { @Override publicvoid run () { for (int i = 0; i < i++) { + "I:" + i);}} ). Start ();
3, Lamda realize "jdk1.8"
Since the runnable interface is a function-type interface
String name = "Thread Object"; // previously must be added Finall, due to LAMDBA, can not be applied New Thread ((), { for (int i = 0; i <; i++) { + "I:" + i); } }). Start ();
Conclusion: As long as the functional interface is given, it is basically possible to use a LAMDA expression or a method reference
Iv. implementation of callable interface "jdk1.5"
Runnable execution complete, cannot callback
Since JDK1.5, for multi-threaded implementation of a callable interface, in this interface than the Runnable interface is the only powerful, you can return the results of execution. This interface is defined in the package java.util.concurrent;
Defined:
@FunctionalInterface Public Interface Callable<v> { throws Exception;}
This generic represents a return value type, and the call () method is equivalent to the run () method.
Use:
class Implements Callable<string> { privateint taket=5; @Override public String call () {// Main method for (int i = 0; I < 10; i++) { if(taket>0) System.out.println ("Sell ticket I:" + taket); } return "tickets sold out! "; }}
Problem: The thread class now does not provide an interface callable interface object operation. How do I start multithreading now??
To analyze the initiated operation, you need to analyze the inheritance structure
First, observe the java.util.concurrent.futuretask<v> structure.
Method invocation
New MyThread5 (); // Get execution Results New Futuretask<>(callable); New Thread (Task); Thread.Start (); System.out.println (Task.get ());
There are no special requirements for this type of approach. General use of Runnable method
Summarize:
1.Thread has single inheritance limitations. However, all threads are guaranteed to start with start in thread.
2.Runnable can avoid single inheritance limitations, it is recommended to use
3.Callable is the only advantage over run. Returns the value of the data. But it's a bit more complicated.
V. For inheriting thread mode and implementing Runnable interface comparison 1, difference and contact
1. Multithreading requires a thread's main class, which either inherits the thread class or implements the Runnable interface
2. Use the Runnable interface to better implement data-sharing operations than the thread class, and use the Runnable interface to avoid single-inheritance limitation issues
2. Analysis
In essence, the two modes must be implemented using the Runnable interface, which avoids the single inheritance limitation, and in addition to the use of the principle, you need to know the two ways of implementing the connection:
The definition structure of the 1.Thread class:
public class Thread implements Runnable
2. Code Analysis
class MyThread2 implements Runnable { private String name; public MyThread2 (String name) { Span style= "color: #0000ff;" >this . Name = name; } @Override public void Run () {
//
for (int i = 0; I < 10; I++ this . Name + "I:" + i); } }}
View Code
Main method
New MyThread2 ("Thread A"); New MyThread2 ("Thread B"); New MyThread2 ("Thread C"); New Thread (mt21). Start (); New Thread (mt22). Start (); New Thread (mt23). Start ();
Analysis of the code structure, the entire code is used in the operation of a proxy design pattern structure, but with the traditional agent structure is different. If you follow the traditional proxy pattern, now you want to start multi-threading, in theory it should be the run () method, but essentially call the start () method, the name does not match. This is because of the long-term development of the product, the previous design pattern is immature. The design pattern developed rapidly after 2000.
In addition to the inheritance associations above, there are some differences: the multithreading implemented by the Runnable interface is more convenient to represent the concept of data sharing than the multiple lines implemented by the thread class.
3. Data sharing Example
Example: Want to have three threads to sell tickets.
Thread implementation
class extends Thread { privateint taket=5; @Override publicvoid run () {// Main method for ( int i = 0; I < 10; i++) { if(taket>0) System.out.println ("Sell ticket I:" +Taket);}}
Main method
New MyThread3 (); New MyThread3 (); New MyThread3 (); Mt31.start (); Mt32.start (); Mt33.start ();
Each thread sells its own ticket, and the data is not shared.
Runnable implementation
class Implements Runnable { privateint taket=5; @Override publicvoid run () {// Main method for ( int i = 0; I < 10; i++) { if(taket>0) System.out.println ("Sell ticket I:" + Taket);}}
The Main method implements
New MyThread4 (); New Thread (MT). Start (); New Thread (MT). Start (); New Thread (MT). Start ();
002-Multithreading Implementation "thread, runnable, Callale, thread, and runnable contrast"