Java Multithreading Basics Summary

Source: Internet
Author: User

background

Java is a multi-threaded way to achieve parallel computing, of course, parallel computing can also be implemented in multiple processes, but process switching costs relatively high. And the process is isolated, inter-process communication mechanism is troublesome, and finally the JVM itself in the operating system in a process, it is not appropriate to start a process, so Java uses multi-threaded way to achieve parallel computing.

from the beginning of Java, multithreading revolves around the Runnable interface and the thread class. It is based on C's P-threading approach, and because of the complexity of multithreading, many of the conceptual knowledge of P-Threading is extended to the Java level, which is unfortunate news for Java developers. But due to the complexity of multithreading, this extension has to be.


1. Instantiation and startup 1.1 Traditional Boot mode runnable Interface

The Runnable interface is the interface in which Java is designed to run a task in the thread body. Implement a task by executing the thread code in the Run method by implementing the Run method of the Runnable interface. The author of the Java programming idea wrote in the book that the naming of the Runnable interface is inaccurate, and that task is more appropriate. The class that implements the interface, indicates that the class can run in parallel running method, that is, run statement execution is not continuous, it is likely to T1 time to execute the first one, T3 time to execute the second. This also brings in atomic operations, primitives, synchronization, mutual exclusion, synergy and other issues.


Thread Class

Thread is a threading class in Java that can be started by instantiating the thread and invoking the Start method. Thread is a class under the Java.lang package, which itself implements the Runnable interface. So the second instantiation and startup of threads can inherit the thread class, and rewrite the Run method, the source code for the Threa class's run () method is as follows:

public void Run () {         if (target! = null) {             target.run ();         }}

   thread after a lot of overloaded construction methods. You can specify the name of the thread, the Runnable object, the owning thread group, and so on. It is generally sufficient to specify only runnable objects. The basic usage of Java threads is basically an introduction to the usage and attention implementation of some methods within the thread class.

new instantiation and start-up methods after 2.jdk1.5

JDK 1.5 is an important version of Java, with a lot of improvements and enhancements, with JDK 1.5 interested in improving some of the Java threading and therefore introducing the Java.util.concurrent package. With the executors and related classes below the package, you can get a Java standard thread pool without the use of other threading frameworks. after JDK 1.5 The Java target minimizes the direct operation of the thread class, so we often see the thread method call after using concurrent package, synchronized keyword can be omitted.


2.1 Executor related

Executors has three main static methods, these three methods adopt the policy mode, encapsulate the thread pool management and operation implementation, return the Executorservice interface implement object uniformly.

Newcachedthreadpool () This method creates a thread pool that can create new threads as needed, but reuses them when previously constructed threads are available. For programs that perform many short-term asynchronous tasks, these thread pools can often improve program performance. Newfixedthreadpool () Creates a thread pool that can reuse the number of fixed threads, running them in a shared linkedblockqueue manner. Newsinglethreadexecutor () Creates a Executor that uses a single worker thread to run the thread in linkedblockqueue manner.

Usage:

Executorservice exec = Executors.newcachedthreadpool (); Exec.execute (new MyThread ()); Exec.shutdown ();


Call execute to join the Runnable object to the thread queue and executorservice to start the thread to run the task according to its own implementation. After the shutdown method executes, it indicates that the thread pool no longer accepts new tasks.

  

2.2 threadfactory

When you instantiate the thread pool, you can pass in an object that implements the Threadfactory interface to customize thread properties, such as batch creation of a daemon thread. Threadfactory This engineering pattern shows that Java threading is designed to accomplish certain concurrent tasks, and executor can perform a similar set of tasks, so these threads can be produced through a factory.

Executorservice exec =executors.newcachedthreadpool (new Threadfactory () {         threadnewthread (Runnable r) {         Thread t = new Thread (r);         T.setdaemon (True);}}); for (int i=0;i++;i<5) Exec.execute (New MyThread ()); Exec.shutdown ();

 

2.3 Tasks with return values:

One of the benefits of multithreading (concurrent computing) is that we can put time-consuming computations in the background so that we can create a UI interface that responds to no animation. The Run method of the Runnable interface is void, without any return value, which is not convenient for some computing needs. After JDK 1.5, you can implement a thread with a return value.

If you want the task to have a return value, then our class will implement the Callable<v> interface, which is a generic interface that can be thought of as a runnable sibling interface. Except that the run method of the Runnable interface cannot throw a checked exception with no return value, but this interface can have a return value and can run out of an exception. This interface specifies a generic method:

V call () throws Exception;

   You can throw a checked exception and return value in this method. The return value is surrounded by the Future<t> object, which guarantees that we get the computed value in a multithreaded environment. Because if the address of a variable is returned directly, we cannot determine whether the variable is evaluated or whether the call method is executed, and the future can be used by the JVM to help us secure the job. And the future has a deeper usage, such as a single thread in a disconnected pool.

Some other operations of the 3.Thread class

The thread class also provides operations such as sleep, SetPriority, Setdaemon, join, and so on, all of which are thread-specific, so they all belong to the method inside the thread. And these operations do not involve the lock, so their operations are generally safe.

3.1 Sleep sleep

The static method of the thread class, which lets the thread hibernate for a period of time, is a native method, in milliseconds. Throws an interruptedexception exception that needs to be captured, which is explained again in the thread interrupt. In general, for example, we will simulate some time-consuming operations in the demo using the Sleep method, allowing the thread to wait for a while, slowing the thread down to reproduce some phenomena.

public class A extends thread{public        void Run () {     try {<span style= ' white-space:pre ' ></span> TimeUnit.SECONDS.sleep (2);     } catch (Interruptedexception e) {     }    }  }

3.2 Set priority, SetPriority

the thread class's object method, which sets the priority of threads and the higher the priority, can be polled as much as possible. The JDK specifies 10 priorities, but the JVM does not map well to most operating systems, and it is important to note that the priority is only a recommendation, not a low priority, which must be performed after the high-priority thread is completed.

The priority of threads is ultimately implemented by the JVM mapping to the OS level, but different OS priorities vary, with fewer windows being 7 and not fixed, and solairs having 2 of the 31 priority. So we generally set the three constants of the thread class to max_priority/norm_priority/min_priority three levels at the time of Setup.

<span style= "White-space:pre" ></span>public class B implements Runnable {<span style= "White-space:pre" ></span>public static void Main (string[] args) {<span style= "White-space:pre" ></span> Executorservice exec = Executors<span style= "White-space:pre" ></span>.newcachedthreadpool (new Daemonthreadfactory ()); <span style= "White-space:pre" ></span>for (int i = 0; i < i++) <span style= " White-space:pre "></span>exec.execute (New Daemonfromfactory ()); <span style=" White-space:pre "></ Span>}<span style= "White-space:pre" ></span> @Override <span style= "White-space:pre" ></span >public void Run () {<span style= "White-space:pre" ></span>thread.currentthread (). SetPriority ( thread.max_priority); <span style= "White-space:pre" ></SPAN>}

3.3 Concession Yield

The static method of the thread class, the native method, represents the yield of the current CPU time, but the concession operation is only a recommendation, the specific will not give up the CPU is also determined by the JVM scheduler. This method can speed up the thread switching frequency during testing and presentation, allowing some problems to occur faster. It is important to note that the concession operation does not operate the lock, that is, if the concession operation occurs within the synchronization block, the thread yields the CPU but does not yield the object lock.

public class C implements Runnable {public static void main (string[] args) {Executorservice exec = Executors.newcachedthre Adpool (New Daemonthreadfactory ()); for (int i = 0; i <; i++) Exec.execute (New Daemonfromfactory ());} @Overridepublic void Run () {Thread.yield (); synchronized (this) {Thread.yield ();}}}


3.4 Getting the current thread CurrentThread

A static method of the thread class, native method, that returns the current thread object. Through this method, you can get some properties, states, etc. in the thread, such as demo or log, often use Thread.currentThread.getName () to output the name of the current thread, convenient to observe.

3.5 Background Thread Setdaemon

The Thread object method, which is not overwritten by the final method. A background thread or daemon thread is a generic service thread provided by the background when the program runs, and this thread is not an integral part of the program , and when all non-background threads end, the program terminates, and they are automatically terminated. and threads that start from the background line of the medium-range construct default to a background thread (that is, thread inherits some of the attributes of the thread that created it)

public class D implements Runnable {public static void main (string[] args) {Executorservice exec = Executors.newcachedthre Adpool (New Daemonthreadfactory ()); for (int i = 0; i <; i++) Exec.execute (New Daemonfromfactory ());} @Overridepublic void Run () {Thread.CurrentThread (). Setdaemon (True);}}

3.6 Joining join

The Thread object method, the final method, is synchronous and throws a Interruptedexecption exception. Join allows a thread to be joined to another thread, but pay attention to who ( thread T1) is added tothe join (THREADT2), because join means to suspend the current thread (T2), The current thread (T2) is not resumed until the target thread (T1) ends.

A join has multiple overloaded methods, which can be called with a time-out parameter, in milliseconds, so that the join can always be returned during the timeout period, and the join can be interrupted.

public class E extends Thread {private double num = 0;public static void Main (string[] args) {e E = new E (); Thread F = new F (e); F.start (); E.start ();} @Overridepublic void Run () {System.out.println ("calculation E"); for (int i = 0; i <; i++) {num = Math.PI * MATH.E + num;} SYSTEM.OUT.PRINTLN ("E calculation complete" + num);} Public synchronized Double Getnum () {return num;}} Class F extends Thread {private E E = Null;public F (e e) {this.e = e;} @Overridepublic void Run () {try {System.out.println ("execute F"); E.join (); System.out.println ("E execution Complete" + e.getnum ());} catch (Interruptedexception e) {System.out.print ("interrupted");}}}

3.7 is Survival IsAlive

The Thread object method, the final method, and the native method, can be used to determine if a thread is alive. Note, however, that thread death exits from run, that is, run executes or executes a return statement. Interrupts do not mean the thread dies, or even if the task handles interrupts correctly, the thread should end, but do not immediately determine the thread object state. For example, if the following does not sleep, the output of two times will be true.


Import java.util.concurrent.timeunit;public classtestalive {public    static void Main (string[] args) throws interruptedexception {        TMt = new TM ();        T.start ();        System.out.println (T.isalive ());        TimeUnit.SECONDS.sleep (1);        T.interrupt ();        TimeUnit.SECONDS.sleep (1);        System.out.println (T.isalive ());    } } class TM Extendsthread {public    void run () {        while (true) {            ///System.out.println ("Surviving ...");            if (thread.interrupted ()) {                return;}}}    }


3.8 Other

Other thread methods, interrupt and isinterrupted will be in the thread interrupt summary, the rest of the stop, resume, suspend, and so on some of the JDK is obsolete, and some are related to Threadgroup. Discard methods know on the line, no need to waste energy, Threadgroup is a failure attempt, not worth wasting energy to study.

4. Thread Groups:

Thread Group is an unsuccessful attempt in Java, and the JDK has been deliberately slowly forgotten, fade it, can not learn. The Java thread Group is a realistic portrayal of the promised escalation theory: "The cost of continuing the error is borne by others, and the cost of admitting the error is at your own risk." So Java has not officially indicated whether the thread group is good or bad.

5. Abnormal capture:

threads are very special, so we cannot catch exceptions that escape from the thread, only in-line processing. But if a runtimeexception is thrown in the code, the error is thrown to the console. After JDK5 you can use executor to create the thread pool and then add an exception handler to it to catch any exceptions thrown by the thread.

PS: The inability to catch exceptions means that we cannot capture any exceptions thrown by run in Try-catch way outside of our thread code. That is, the following code is not correct.

try {    Threadm =new Thread (New Runnable () {public        void run () {            throw newruntimeexception ();        }    });    M.start ();} catch (Exceptione) {    System.out.println ("Caught Exception");}


Thread.uncaughtexceptionhandler interface

This interface is the interface that appears after JDK1.5, the internal interface of the thread. Set the instance object of the interface to the thread object (T.setuncaughtexceptionhandler) or to the global default exception handler (thread.setdefalutuncaughtexception) to catch the exception thrown in the thread.

PS: The exception discussed here is the exception that is thrown by our task code and should not be included in the interrupt exception for the thread.

Publicclassuncatchexceptionthread extends Thread {    publicvoid run () {        throw newruntimeexception ("Error! ");    }     publicstatic void Main (String[]args) {        Uncatchexceptionthreadt =new uncatchexceptionthread ();        Thread.setdefaultuncaughtexceptionhandler (New Thread.uncaughtexceptionhandler () {public            void Uncaughtexception (Threadt, Throwablee) {                System.out.println ("Exception occurred:" + e.getlocalizedmessage ());}        );        try {            executorserviceexec = Executors.newcachedthreadpool ();            Exec.execute (t);//This exception is more friendly!            //T.start ();        } catch (Exceptione) {            System.out.println ("caught exception" + E);}}}    

6.TimeUnit

Timeunit is a new enumeration class in JDK 1.5, located under the Java.util.concurrent package. The main intent of the enumeration is to free the program ape from the "tyranny" of the millisecond. Before JDK 1.5, if we wanted to do something based on the time unit, like sleep 3 seconds, then we'd need to calculate how many milliseconds 3 equals, although the calculation is not complicated, but with Timeunit, We can directly call Timeunit's seconds's sleep to pass in a long value, Timeunit related methods automatically help us to convert the time unit.

Using the Timeunit class can make your code clearer and easier to read, after all, we may be reading code longer than we write code.

@Overridepublic void Run () {try {//traditional time notation long mills = 3 * 1000;//sleeps 3 seconds, one second equals 1000 milliseconds thread.sleep (mills);//Timeunit Sleep Timeu Nit. Seconds.sleep (3);//hibernate 3 seconds} catch (Interruptedexception e) {System.out.print ("interrupted");}}

Summary:

Java multithreading is the basis of Java implementation concurrency, multithreaded programming itself is not fresh, nor Java-specific, but the Java language itself supports multi-threading, which is much easier than the C and other languages to write multithreaded code, and Java itself to eliminate the OS level of thread differences. The basic syntax of Java multithreading is very simple, the more difficult is the basic concept. These studies are easier to understand if you have knowledge of computer operating system process scheduling and management.

The basis of Java multithreading is to first understand the various methods and concepts of thread, understand the four states of thread, and the transitions between states. Can reasonably use the various methods provided by the thread class to accomplish some things. After understanding the Java Multithreading Foundation, we can better study the synchronization and coordination mechanism between Java multithreading. For the concurrent package provided by JDK 1.5, it is more appropriate to understand the basics before examining the package. Many concurrent experts recommend using Java's traditional approach, and then replacing your implementation with concurrent package-related tools when there are special scenarios or need performance optimizations. Compare the concurrent package to provide a lot of things are too advanced, and multithreaded performance tuning itself should be based on the actual scene or even the machine, the JVM version of the original debugging.



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Multithreading Basics Summary

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.