Java- third in three kinds of ways to create a thread

1, Java threads using Thread class represents all thread object must be an instance of the Thread class or subclass.

    When a thread inherits the Thread class, you can directly use this to get the current thread, getName Thread object () method returns the name of the current thread, so you can directly call the getName () method returns the name of the current thread.

    Thread.currentThread (): This method always returns the currently executing thread object.

2, create a thread mode 1: Create a thread class inheritance Thread class

    To create a thread in this way generally:

    1 "subclass definition Thread class, the class and override run () method , a thread which thread of execution .

    2 "create an instance of a subclass of Thread, Thread object.

    3 "calling thread object start () method to start a thread.

3, create a thread mode 2: implement Runnable

    To create a thread in this way generally:

      1 "defines the Runnable interface implementation class, interface and override the run () method , the method body run () method of the thread is likewise thread of execution .

      2 "Create an instance of Runnable interface implementation class, and that instance as a target to create Thread Thread object, the Thread object is the real thread object . Thread object run essentially responsible for the implementation object implementation class () method body.

      3 "the calling thread object's start () method to start the thread.

4, Callable and Future create a thread: create a thread that returns a value

    To create a thread in this way generally:

       1 "Create Callable interface implementation class, and implements call () method , which a thread of execution , and the process returns a value. Then create an instance of the implementation class.

       Return Value 2 "FutureTask used to wrap a Callable object class, the object encapsulates FutureTask Callable object of the call () method.

       3, "Using FutureTask Thread object as a target object to create and start a new thread.

       4 "call FutureTask object get () method to get the return value after the end of the sub-thread execution.

Guess you like

Origin www.cnblogs.com/ZeroMZ/p/11361193.html