Understanding of Multithreading (Introduction)

Source: Internet
Author: User
Tags thread class ticket

Process : A program that is in progress. In fact, a process is a memory allocation space when an application runs.

thread : It is actually a program execution control unit in the process, an execution path. The process is responsible for the application's spatial labeling. Threads are responsible for the order in which the application executes.

All in all , a process has at least one thread running, and when multiple threads appear in a process, the application is called a multithreaded application, and each thread has its own execution space, its own method area, and its own variables in the stack area.

When the JVM starts, it first has a main thread, which is responsible for the execution of the program, and the main function is called. The code executed by the main thread is in the main method.

When garbage is generated, the garbage collection action is not required to complete the main thread, because in this case, the code execution in the main thread will stop, will run the garbage collector code, inefficient, so a separate thread responsible for garbage collection.

the principle of randomness : Because of the fast switching of the CPU , which thread gets the execution of the CPU and which thread executes it.

returns the name of the current thread: Thread.CurrentThread (). GetName ()

The name of the thread is defined by the:thread- number. Numbering starts from 0 .

The code for the thread to run is stored uniformly in the Run Method the.

the thread must be run by using the method specified in the class. Start method . (after startup, one more execution path)

Start Method: 1 ), started the thread,2), and let the JVM invoke the run method.

The first way to create a thread is to inherit the thread, which is a subclass of the run method.

Steps:

1 , the definition class inherits the Thread class;

2 , the purpose is to replicate the run method, and the code that will let the thread run is stored in the run method;

3 , create a thread object by creating a subclass object of the thread class;

4 , call the thread's start method, open the thread, and execute the run method.

Thread State:

is created: Start ()

Run: Be qualified for execution and have the right to execute;

Freeze: Sleep (time), wait () -Notify () wake up; thread releases execution and releases execution eligibility;

Temporary blocking status: The thread has the CPU execution qualification, does not have the CPU execution right;

Extinction: Stop ()

The second way to create a thread: Implement an interface Runnable.

Steps:

1 , the definition class implements the Runnable interface.

2 , overwriting the run method in the interface (used to encapsulate the code that the thread is running).

3 , the thread object is created through the thread class;

4 , the subclass object that implements the Runnable interface is passed as the actual parameter to the constructor in the Thread class.

Why should it be passed? Because you want the thread object to explicitly run the object that the Run method belongs to.

5 , call the start method of the Thread object. Open the thread and run the running method in the Runnable interface subclass.

Ticket t = new Ticket ();

/*   directly Create Ticket object, not creating a thread object.

Because the object can only be created through the new thread class, or the subclass of the new thread class.

So eventually you want to create a thread. Since there is no subclass of the thread class, you can only use the thread class.

*/

thread T1 = new Thread (t);  // creates a thread.

/*   as long as the T as a Thread The actual parameters of the constructor of the class are passed in to complete the thread object and T the association between

Why pass T to the constructor of the Thread class? In fact, the code run method that the thread is running is defined.

*/

T1.start ();

Why should there be a Runnable interface?

1 : by inheriting the thread class, you can complete the creation of multithreading. However, this approach has a limitation, if a class already has its own parent class, it is not possible to inherit the Thread class because of the limitations of Java single inheritance.

However, some of the code in this class needs to be executed concurrently by multiple threads. What then?

Java provides an interface Runnableonly if additional functionality is extended to the class. The Run method is defined in this interface, in fact the definition of the run method is to store code that is multithreaded to run.

Therefore, it is common to create threads in a second way.

Because implementing the Runnable interface avoids the limitations of single inheritance.

2 : in fact, it is not similar in the need to be multithreaded execution of code to extract. Define the location of the code that is multithreaded to run separately into the interface. Provides the prerequisites for extending the functionality of other classes.

So when the thread class describes threads, the internally defined run method is also derived from the Runnable interface.

Implementing the Runnable interface avoids the limitations of single inheritance. Also, inheriting thread, you can make a subclass of the method in the thread class. However, it is more convenient to implement the Runnable interface just to define the location of the thread code, without the need for this replication action. So the Runnable interface encapsulates the task that the thread is performing as an object .

-------------------------------------------------------

// Interview

New Thread (new Runnable () {// anonymous

public void Run () {

System.out.println ("runnable run");

}

})

{

public void Run () {

System.out.println ("Subthread run");

}

}.start ();

// Result:subthread run

---------------------------------------------------------

Try {

Thread.Sleep (10);

}catch (Interruptedexception e) {}// when the thread is deliberately paused, simulate the CPU switchover situation.

reasons for multithreading security issues :

By illustration: When a thread executes multiple statements and the same data is executed, other threads participate in the process and manipulate the data. result in the creation of the wrong data.

Two factors are involved:

1 , multiple threads are manipulating the shared data.

2 , there are multiple statements that perform operations on the shared data.

Cause: These multiple statements are executed by another thread at some point when they are executed by a thread and have not finished executing.

the principle of solving security problems :

As long as the statement that the operation shares data has been executed by a thread during a certain period of time, it can be resolved by other threads that cannot come in during execution.

How to do multi-sentence operation shared data code encapsulation?

Java provides a workaround: is to synchronize the code block.

Format:

synchronized ( object ) { // any object can be. This object is the lock.

Code that needs to be synchronized;

}

Multi-Threading Understanding (Introduction)

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.