Java Threading---thread,runnable,callable basic learning

Source: Internet
Author: User
Tags ticket

Java uses the thread class to represent threads, and all field objects must be instances of the thread class or its subclasses. The role of each thread is to accomplish a certain task, in effect, to execute a program flow. Java uses the thread execution body to represent this program flow.

1. Inheriting the thread class to create threads

The steps to start multithreading are as follows:
(1) Define a subclass of the thread class and override the run () method of the class, which represents the task that the class thread needs to complete. Therefore, the run () method is called the thread execution body.
(2) Create an instance of the thread subclass, that is, create a threading object.
(3) Call the thread's Star () method to start the thread.

The relevant code is as follows:

/** * Inherit the inner class of thread to buy tickets example * /     Public  class firstthread extends Thread{        Private intIPrivate intTicket =Ten;@Override         Public void Run() { for(;i< -; i++) {//When inheriting thread, use this directly to get the current thread, getName () get the name of the current thread//LOG.D (Tag,getname () + "" +i);                if( This.ticket>0) {LOG.E (TAG, getName () +", Sell ticket: ticket="+ ticket--); }            }        }    }Private void Starticketthread() {LOG.D (TAG,"Starticketthread,"+thread.currentthread (). GetName ()); Firstthread Thread1 =NewFirstthread (); Firstthread thread2 =NewFirstthread (); Firstthread thread3 =NewFirstthread ();        Thread1.start ();        Thread2.start (); Thread3.start ();//Open 3 threads to buy tickets, each thread sold 10, a total of 30 tickets}

Operation Result:

You can see that the number of votes entered by 3 threads is discontinuous, note: Ticket is an instance property of Firstthread, not a local variable, but because each time a program creates a thread object, it needs to create a Firstthread object, and all multiple threads do not share the instance's properties.

2. Implement Runnable interface creation thread

Note: public class Thread implements Runnable

(1) Define the implementation class for the Runnable interface, and override the run () method of the interface, which is also the thread execution body of the thread of the Run () method.
(2) Create an instance of the Runnable instance class that is the target of the thread to create the thread object, which is the real object.

The relevant code is as follows:

/** * Implement Runnable interface, create thread class * /     Public  class secondthread implements Runnable{        Private intIPrivate intTicket = -;@Override         Public void Run() { for(;i< -; i++) {//If the thread class implements the Runnable interface                //Gets the current thread and can only get the current thread name with Thread.CurrentThread ()LOG.D (Tag,thread.currentthread (). GetName () +" "+i);if( This.ticket>0) {LOG.E (TAG, Thread.CurrentThread (). GetName () +", Sell ticket: ticket="+ ticket--); }            }        }    }Private void starTicketThread2() {LOG.D (TAG,"StarTicketThread2,"+thread.currentthread (). GetName ()); Secondthread Secondthread =NewSecondthread ();//Create a new thread by using new threads (Target,name)        NewThread (Secondthread,"Ticket man 1"). Start ();NewThread (Secondthread,"Ticket Man 2"). Start ();NewThread (Secondthread,"Ticket man 3"). Start ();//Although 3 threads were opened, only 100 tickets were purchased.}

Operation Result:

You can see that the number of votes entered by 3 threads is continuous, and the Runnable interface is used to create multiple threads that can share the properties of an instance of a thread class. This is because, in this way, the Runnable object created by the program is only the target of the thread, and multiple threads can share the same target, so multiple threads can share instance properties of the same thread class (which should actually be the target class of that thread).

3. Creating threads with callable and future

Starting with Java 5, Java provides the callable interface, which is an enhanced version of Runnable, and callable provides Class A call () method that can act as a thread executor, but the call () method is more powerful.
(1) The call () method can have a return value
(2) The call () method can declare an exception to be thrown

So we can provide a callable object as the target of thread, and the execution body of that thread is the call () method of the Callable object. At the same time, Java 5 provides a future interface to represent the return value of the call () method in the callable interface, and provides a Futuretask implementation class that implements the class future interface and implements the Runnable interface-which can be used as thread The target of the class.

The startup steps are as follows:
(1) Create an implementation class for the callable interface and implement the call () method, which will act as the executing body of the thread, and the call () method has a return value.
(2) Create an instance of the callable implementation class, using the Futuretask class to wrap the callable object, which encapsulates the return value of the call () method.
(3) Use the Futuretask object as the target of the thread object to create and start a new thread.
(4) Call the Get () method of the Futuretask object to get the return value after the child thread has finished executing.

The relevant code is as follows:

/** * Use callable to implement threading class */     Public  class thirdthread implements callable<Integer>{        Private intTicket = -; @Override PublicInteger Call () { for(inti =0;i<Ten; i++) {//Gets the current thread and can only get the current thread name with Thread.CurrentThread ()//LOG.D (Tag,thread.currentthread (). GetName () + "" +i);                if( This.ticket>0) {LOG.E (TAG, Thread.CurrentThread (). GetName () +", Sell ticket: ticket="+ ticket--); }            }returnTicket }    }Private voidStarcallablethread () {Thirdthread Thirdthread =NewThirdthread (); futuretask<integer> task =NewFuturetask<integer> (Thirdthread);NewThread (Task,"Thread with return value"). Start ();Try{Integer integer = Task.get (); LOG.D (TAG,"Starcallablethread, the return value of the child thread ="+integer); }Catch(Interruptedexception e)        {E.printstacktrace (); }Catch(Executionexception e)        {E.printstacktrace (); }    }

Operation Result:

Note: The call () method of callable allows the declaration to throw an exception and allows the return value.
The program finally calls the Get () method of the Futuretask object to return the return value of the call () method, causing the main thread to be blocked until the call () method ends and returns.

4. Comparison of three different ways
Create multithreading in a way that inherits the thread class
Disadvantage: The thread class has been inherited and can no longer inherit from other parent classes.
Advantage: Write simple
Create multithreading in a way that inherits the Runnable,callable interface
disadvantage: Programming is a little bit more complicated if you need access to the current thread must use Thread.CurrentThread ()
Advantages:
(1) Other classes can also be inherited
(2) Multiple threads can share a target object, so it is very suitable for multiple identical threads to handle the same resource, thus separating the CPU, code and data to form a clear model, and a better embodiment of the object-oriented thinking.

Java Threading---thread,runnable,callable basic learning

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.