Concurrent programming--java built-in threading mechanism "on"

Source: Internet
Author: User

If you don't understand multithreaded programming, you can't really understand javase and JDK source code, because threading features are tightly integrated with the Java language.

How to learn multithreaded programming? That seems to always seem a bit mysterious. First of all, it is necessary to thoroughly understand the basic principles and mechanisms of concurrent programming, otherwise, just learn to use those keywords, classes of moves, I am afraid only to get superficial understanding, because the difficulty of multithreaded programming is that in any case can work correctly, easily writing Programs that appear to work but would fail at any time. You must have a deeper understanding of the threading mechanism to know what you are doing, and secondly, multi-threaded routines are not mysterious, and several basic points are: 1. How to define, execute and terminate tasks; 2. How to allow concurrent tasks to securely access shared resources; 3. How to enable better collaboration and communication between tasks; 4. Avoid starvation and deadlock. After understanding these points, we must find the corresponding mechanism from the language.

The next two articles will summarize the Java built-in threading mechanism, where the code examples are written by myself, with errors and omissions, and I implore to point out.

1. Terminology:
Conceptual Level: task: Concurrency refers to multiple tasks concurrently.
Technical Level: Threads: threads are implementation mechanisms for concurrent execution of multiple tasks, and thread-driven task execution.
In
a single-threaded environment, only one task is executed, that is, a single task entity from the main method portal, which is driven and executed by the thread assigned to main, which can be called the "main thread".

2. Define the task:

① implements the runnable interface:
Public
class Xxx implements Runnable {
Public
void Run () {//codes}
//Codes
}
② inherits the thread class:
Public
class Xxx extends Thread {
Public
void Run () {//codes}
//Codes
try to use the first way: ① the chance to inherit only once, ② avoid creating explicit thread objects, but instead give the executor to manage the start, execution, and termination of the task.

Start Task: New Thread (Runnable). Start ().

3. Start, execute, and manage tasks: Using actuators Executorservice

Java provides a number of high-level tools to better start, execute, and manage tasks. Understanding the underlying mechanism, using high-level tools, like assembly language is good for understanding the internal details of C, but should always be programmed with C. The existence of any thing has its most valuable occasion, some things exist to support the better things, therefore, according to different occasions to choose the most appropriate tool.

Create an actuator in one of the following four ways, such as executorservice es = Executors.newcachedthreadpool ();
Øexecutors.newfixedthreadpool (): Creates a thread pool with a fixed number of threads that can be reused for idle threads;
Øexecutors.newcachedthreadpool (): The number of threads is variable, the idle thread can be reused ;
Øexecutors.newsinglethreadexecutor (): Single-threaded actuator, sequential execution of tasks;
Øexecutors.newscheduledthreadpool (): Number of fixed threads, support for deferred and recurring tasks.
① performing the tasks in the executor: execute (runnble) and submit (callable<t>) methods
② shutdown executor no longer accepts task: shutdown Method "IsShutDown method determines whether the actuator is closed"
③ terminating the task in the executor: Shutdownnow method

④ wait for the task to complete: awaittermination (Long, Timeunit) method "isterminated method to determine whether the task has been fully executed in the executor"

The following example defines two threads, where the main thread prints the information every 2 seconds, and the thread receives an integer input from the console and prints it out. Once the user enters 0 or enters illegal data, the slave thread exits, thereby terminating the main thread by setting the end tag Endflag.

Package Threadprogramming.basic;import Java.util.scanner;import Java.util.concurrent.timeunit;public class ioconcurrency {private static Scanner s = new Scanner (system.in);p rivate static volatile Boolean endflag = False;public St atic Boolean end () {return endflag = = true;} public static void Setflag () {Endflag = true;} public static Boolean Getflag () {return endflag;} public static void Main (string[] args) {System.out.println ("Enter the main thread."); /from a thread reads an integer from the standard input and outputs it to the console new thread (new Runnable () {public void run () {System.out.println ("Enter into Thread:" + Thread.curr    Entthread (). GetName ()); try {while (true) {int i = S.nextint ();    System.out.println (Thread.CurrentThread (). GetName () + "\tread:" + i);    if (i = = 0) {System.out.println ("Exit from Thread:" + thread.currentthread (). GetName ());    Break }}}catch (Exception e) {System.out.println ("Caught:" + e.getmessage ()); System.out.println ("Exit from Thread:" + thread.currentthread (). GetName ());} finally {IOCONCURRENCY.SEtflag ();}}). Start ();//The main thread prints one message per 2s while (!end ()) {Long start = 2000;try {TimeUnit.MILLISECONDS.sleep (start);} catch (Interruptede    Xception e) {System.out.println ("interrupted in main thread.");        SYSTEM.OUT.PRINTF ("In main thread:%d Ms Passed.\t", start);    System.out.printf ("The END flag:%b\n", Getflag ()); }system.out.println ("Exit the main thread.");}}

4. Task definition, execution, and result acquisition with return values
*① implements the callable <T> interface and specifies the parameter type T;
*② Implementation method: Public T-call (), where T is the specific type that has been specified.
*③ creates threads and uses executorservice.submit (callable<t> Task) to execute;
*④ creates future<t> to store task execution objects.

*⑤ uses the Get () method of the Future<t> object to obtain the execution result.


In the example below, each thread accepts an integer value of Givennum, calculates the sum of squares of the 1-givennum, and returns the result.

Package Threadprogramming.basic;import Java.util.arraylist;import Java.util.list;import Java.util.concurrent.callable;import Java.util.concurrent.executionexception;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import java.util.concurrent.Future; public class Returnablethread implements callable<integer> {private int givennum;public returnablethread (int Givennum) {this.givennum = Givennum;} /** * Calculates the sum of squares of 1-givennum */@Overridepublic Integer call () throws Exception {int sum = 0;for (int i=1; I <= givennum; i++) {sum + = i*i;} return sum;} public static void Main (string[] args) {Executorservice es = Executors.newcachedthreadpool (); list<future<integer>> results = new arraylist<future<integer>> (); for (int i=1; i<=10; i++) { Results.add (Es.submit (New Returnablethread (i))); Es.shutdown (); for (future<integer> result:results) {try {System.out.println (Result.get ());} catch ( Interruptedexception e) {e.printstacktrace ();} CATCH (executionexception e) {e.printstacktrace ();}}}} 


5. Task Pause :
calling " Thread.Sleep (n), N: Milliseconds" or "TimeUnit.MILLISECONDS.sleep (n), n milliseconds" causes the thread to hibernate for a period of time "in a blocked state", after which the thread wakes up automatically.

If you make a thread call the interrupt () method during a threads hibernation, a break exception interruptedexception is thrown , which causes the thread to terminate the blocking state "terminate task."

The following example shows the use of the sleep method and how to break the sleeping thread.

Package Threadprogramming.basic;import Java.util.concurrent.executorservice;import Java.util.concurrent.Executors Import Java.util.concurrent.timeunit;public class Sleepinterruption {public static void main (string[] args) { Executorservice es = Executors.newcachedthreadpool (); for (int i=1; I <= 5; i++) {Es.execute (new Sleeper (i*1000 + 500)); }try {TimeUnit.MILLISECONDS.sleep;} catch (Interruptedexception e) {System.out.println ("interrupted!");} Es.shutdownnow ();}} Class Sleeper implements Runnable {private int millis;public Sleeper (int millis) {this.millis = Millis;} public void Run () {Long start = 0, end, passed;try {start = System.currenttimemillis (); TimeUnit.MILLISECONDS.sleep (Millis);} catch (Interruptedexception e) {end = System.currenttimemillis ();p = End-start; System.out.printf ("Waken up! Requiring%6d ms, sleep%6d MS, rest%6d ms\n ", Millis, passed, millis-passed);} System.out.println ("Time:" + Millis);}}

6. Task Scheduling tips:
calling the Thread.yield () method suggests that thread scheduling and dispatcher can give the CPU to other threads for use. Note that it is only a hint and there is no guarantee that it will. For extremely important control and scheduling, this method cannot be relied upon, and the Thread.yield () method can be used to simulate certain executions that appear to be atomic operations (such as count++), thus causing minor threading errors to emerge earlier.
7. Thread exception: Try to handle the exception within the task, do not let the exception escape to a wider range.
8. Background thread:
Ø to provide common services for non-background threads, the optional components in the program;
Ø when all non-background threads are terminated (including the main main thread also exits ), the program will not be able to block the final
all background threads will be terminated immediately;
Ø Normal Thread call method Setdaemon (true) can become a background thread;
Ø The thread created by the background thread automatically becomes a background thread.
Ø by implementing thread Factory Threadfactory can be used to generate custom properties of the thread, and its implementation class passed
to

Executorservice (Threadfactory) constructor to execute the factory that generated the background thread. The following example illustrates the use of a background thread: Customizing the background thread factory through Daemonthreadfactory, passing in parameters so that each background thread has a service name and prints it in the task. As you can see from the output, all the background threads end up when main and the non-background thread that computes the multiplication are finished.

Package Threadprogramming.basic;import Java.util.concurrent.executorservice;import Java.util.concurrent.Executors ; Import Java.util.concurrent.threadfactory;import Java.util.concurrent.timeunit;public class DaemonThreadDemo { private static string[] Services = new string[] {"Data Manager", "Network", "Event reporting", "Media Devices", "Memory Monitor "};p ublic static void Main (string[] args) {Executorservice es = Executors.newcachedthreadpool (new Daemonthreadfactory ()); Create a background thread for (int i=0; i < 5; i++) {Es.execute (new Daemonservicethread (Services[i]));} Es.shutdown ();//create non-background thread the new thread (new Runnable () {@Overridepublic void Run () {for (long i=1; i < 20000; i++) {for (Lon G J=1; J < 20000; J + +) {Long m = i * j;}} System.out.println ("Exit from:" + thread.currentthread (). GetName ());}). Start ();//main thread ends System.out.println ("Quit Main.");}} Custom Threading Factory class Daemonthreadfactory implements Threadfactory {@Overridepublic thread newthread (Runnable r) {Thread T = new Thread (r); T.setdaemoN (True); return t;}} Background thread: Provides service at intervals class Daemonservicethread implements Runnable {private String servicename;public daemonservicethread ( String serviceName) {this.servicename = ServiceName;} @Overridepublic void Run () {while (true) {try {TimeUnit.MILLISECONDS.sleep],} catch (Interruptedexception e) { System.out.println ("interrupted."); System.out.println (Thread.CurrentThread (). GetName () + "providing service:" + ServiceName + "... ");}}}


9. Anonymous Threads:

Anonymous threads (anonymous inner classes) can be created inside the class and inside the method. As you can see, anonymous internal classes are ubiquitous in multi-threaded program design, especially in GUI programming. Incidentally, the Thread.Join method is shown, which suspends the calling thread until the thread T of T.join executes, or an interrupt exception is generated.

Package Threadprogramming.basic;public class Joiner extends thread {private thread jthread;public Joiner (thread jthread) {this.jthread = Jthread;} @Overridepublic void Run () {try {jthread.start (); Jthread.join ();} catch (Interruptedexception e) {System.out.printl N ("interrupted.");         } System.out.println ("Enter thread:" + thread.currentthread (). GetName ());  for (int i = 0; i < i++) System.out.printf ("Print [%d]\n", I); System.out.println ("Exit thread:" + thread.currentthread (). GetName ());} public static void Main (string[] args) {System.out.println ("Enter thread:" + thread.currentthread (). GetName ()); Thread joinerthread = new Thread () {public void run () {System.out.println ("Enter Thread:" + thread.currentthread ().   GetName ());   System.out.println ("Joiner do something ...");   for (int i=0; i <; i++) {System.out.printf ("%d *%d =%d\n", I, I, i*i);   } System.out.println ("Exit thread:" + thread.currentthread (). GetName ());     }       }; New JoIner (Joinerthread). Start (); System.out.println ("Exit thread:" + thread.currentthread (). GetName ());}}


Concurrent programming--java built-in threading mechanism "on"

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.