Java Concurrency Tool Learning 02 Thread object (Threads object) Those things

Source: Internet
Author: User
Tags thread class

Each thread is associated with a thread instance. There are two basic strategies for creating threads.
+ Instantiate a thread instance, the program asynchronously creates a new thread to perform the task (facilitates direct control of thread creation and management)
+ Transfer task to executor (executor) execution (abstract thread management from other parts of the application)
This section uses method one to create threads, which are described in the following sections of the actuator.

1. Define and create a thread
There are two ways to define a thread that defines the business logic that a thread needs to provide thread execution:
(1) Implement Runable interface

 Public class Implements Runnable {    publicvoid  run () {        System.out.println ("Hello from a thread!" );    }      Public Static void Main (String args[]) {        (new Thread (new  hellorunnable ())). Start ();}    }

(2) Inherit the thread class, implement the method run ()

 Public class extends Thread {    publicvoid  run () {        System.out.println ("Hello from a thread!" );    }      Public Static void Main (String args[]) {        (new  hellothread ()). Start ();}    }

How do you choose between the two styles above? The first style is more common, since implementing the Runnable interface can also inherit classes outside the thread class. The second style is easy to use in a simple application, but is limited by the descendant class of thread. This section mainly uses style one, which separates threads (thread) from tasks (Runnable).

Style is not only more flexible than style, but also more suitable for advanced API (thread pool, etc.) than style.

2. Suspend a thread with sleep
Thread.Sleep can pause the current thread and specify the time to pause. When paused, the thread's time slice will be used by other running threads or processes in the system.
The Sleep method overloads two versions, one for the millisecond and the other to nanosecond.
Of course, sleep time is not guaranteed to be accurate, which is limited by system equipment. The thread can also terminate during sleep due to thread interruption (interrupts).

 Public classSleepmessages { Public Static voidMain (String args[])throwsinterruptedexception {String importantinfo[]= {            "Mares Eat oats",            "Does Eat oats",            "Little Lambs eat Ivy",            "A kid'll eat Ivy too"        };  for(inti = 0; I<importantinfo.length; I++) {            //Pause for 4 secondsThread.Sleep (4000); //Print a messageSystem.out.println (Importantinfo[i]); }    }}

You can see that the main function throws a Interruptedexception exception. This exception is triggered by other threads interrupting the current process while the current thread is in sleep.

3. Thread interrupt (interrupts)
Interrupts (interrupt) indicate that a thread should stop what it is doing. It is up to the developer to determine how the thread responds to interrupts.
The interrupt command is sent to the thread by calling the thread's interrupt method. In order for the interrupt mechanism to work correctly, the interrupted thread should be able to support interrupts.
(1) Support interruption
How do I get a thread to support interrupts? It depends on what the thread is Duzi. If it calls a throw interruptedexception, the usual practice is to get (catch) the exception after the direct return (return). As in the above example, if executed in runnable, it should be modified to the following:

 for (int i = 0; i < importantinfo.length; i++) {    //  Pause for 4 seconds    try  {        thread.sleep (4000);     Catch (interruptedexception e) {        //  We ' ve been interrupted:no more messages.        return ;    }     // Print a message     System.out.println (Importantinfo[i]);}

Many methods are thrown interruptedexception, such as sleep, which we can deal with as above.

But what if a thread executes for a long time and the calling method does not throw interruptedexception? The answer is to call Interruptedexception periodically and return true if the thread is interrupted. As follows:

 for (int i = 0; i < inputs.length; i++) {    heavycrunch (inputs[i]);     if (thread.interrupted ()) {        //  We ' ve been interrupted:no more crunching.        return ;    }}

The above detects an interrupt to exit directly, and usually throws an exception manually in a more complex program:

if (thread.interrupted ()) {    thrownew  interruptedexception ();}

(2) Interrupt sign (the INTERRUPT Status flag)

The interrupt mechanism (interrupt mechanism) determines the thread break state through an interrupt flag inside the thread. When calling the interrupt method, set the value for this flag. The flag is emptied when the thread views the thread state by calling thread.interrupted. isinterrupted queries with non-static methods will not empty the flag, but also can find the status.
The flag is also emptied when the interruptedexception exception is thrown.

4. Join (Joins)
The Join function allows one thread to wait for the other thread to run and then continue. If T is a running thread,
Call

T.join ()

Will cause the current thread to pause until the T thread terminates. The overloaded function of the Join function can specify a long wait time, of course, this time is not guaranteed to be accurate.
Join, sleep throws an exception because of a thread break.

5. Program Example

 Public classSimplethreads {//Display A message, preceded by//The name of the current thread    Static voidthreadmessage (String message) {string ThreadName=Thread.CurrentThread (). GetName (); System.out.format ("%s:%s%n", ThreadName, message); }    Private Static classMessageloopImplementsRunnable { Public voidrun () {String importantinfo[]= {                "Mares Eat oats",                "Does Eat oats",                "Little Lambs eat Ivy",                "A kid'll eat Ivy too"            }; Try {                 for(inti = 0; I<importantinfo.length; I++) {                    //Pause for 4 secondsThread.Sleep (4000); //Print a messagethreadmessage (Importantinfo[i]); }            } Catch(interruptedexception e) {threadmessage ("I wasn ' t done!"); }        }    }     Public Static voidMain (String args[])throwsinterruptedexception {//Delay, in milliseconds before//We interrupt Messageloop//thread (default one hour).        LongPatience = 1000 * 60 * 60; //If command line argument//present, gives Patience//In seconds.        if(Args.length > 0) {            Try{Patience= Long.parselong (Args[0]) * 1000; } Catch(NumberFormatException e) {System.err.println ("Argument must is an integer."); System.exit (1); }} threadmessage ("Starting Messageloop Thread"); LongStartTime =System.currenttimemillis (); Thread T=NewThread (NewMessageloop ());        T.start (); Threadmessage ("Waiting for Messageloop thread to finish"); //Loop until Messageloop//thread Exits         while(T.isalive ()) {Threadmessage ("Still Waiting ..."); //Wait Maximum of 1 second//For Messageloop thread//To finish.T.join (1000); if((System.currenttimemillis ()-StartTime) >Patience)&&t.isalive ()) {Threadmessage ("Tired of waiting!");                T.interrupt (); //shouldn ' t be a long now//--Wait indefinitelyT.join (); }} threadmessage ("Finally!"); }}

Java Concurrency Tool Learning 02 Thread object (Threads object) Those things

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.