The establishment of multi-threading method

The establishment of multi-threading method

1: Create a subclass of the Thread class

java.lang.thread categories: descriptive thread class, we want to achieve a multi-threaded program, it is necessary to inherit the Thread class

Implementation steps:

  • Create a subclass of the Thread class and override the run method, set the thread task
  • Create a sub-class object, Thread class method calls start class, open a new thread, the method is performed automatically run
Multi-threaded process, the understanding of memory

Here Insert Picture Description1: a Thread subclass object of the same time can only execute a start,
2: Call the start method is actually open up a stack space run method, and other threads independently of each
3: invoke the run method will not stack space to open up, so not achieve multi-threaded


Get the name of the thread:

1: Use getName Thread class ()
object calls: String getName Returns the name of this thread
wrote in the thread run method: System.out.println (super.getName ());
2: can first obtain the currently executing thread, using thread method getName () to get the thread name
static thread currentThread () returns the current thread of execution objects in the
writing thread run method: thread t = Thread.currentThread (); System.out.println (t .getName ());

Set the name of the thread:

1: call setName method

person.setName("张三");

2: Thread subclass constructor with established parameters, call the parent class constructor parameter passing, so that helped change the name of the parent class

public Person2(String name) {
super(name);}

2: Create a class that implements the interface Runable

java.lang.Runnabel interface should be implemented by those who intend to carry out its example by a thread class, the class must define a run method
created after implementation class, to be passed in the Thread class constructor to
java.lang.Thread class constructor:
Thread (Runnable target) Allocates a new Thread objects
Thread (Runnable target, String name) Allocates a new Thread object and a name

Implementation steps:
1: Create a class that implements Runnable interface, and override the run method to set the thread task
2: Create an object implementation class, and create an object of the Thread class, the incoming object that implements the class constructor method
3: Call the method of the Thread class start

Implement Runnble interface to create a multithreaded program benefits:
1: avoid the limitations of single inheritance of
a class can only inherit a class that implements the Runnable interface can also inherit from other classes, implement other interfaces
2: Enhanced extension of the program, j reduced the coupling of the program
implementation Runnblej interface, the set tasks and open a new thread thread separation,

Published 13 original articles · won praise 12 · views 2360

Guess you like

Origin blog.csdn.net/qq_44333505/article/details/105211388