Bi Xiangdong Java Video Learning note "DAY11-DAY13 multithreading"

Source: Internet
Author: User
Tags thread class ticket

Java_day12 multithreading

Process: A program that is in progress ( literal translation ).

Thread: A control unit ( execution path ) in the process that is responsible for program execution

Multiple paths can be executed in a process, called multithreading.

There must be at least one thread in a process.

Multiple threads are opened to run multi-part code at the same time.

Each thread has its own running content. This content can be called a task that the thread will perform.


Multithreading Benefits: Solves the problem of multiple parts running at the same time.

The disadvantage of multithreading: too many threads back to the reduction of efficiency.

In fact, the implementation of the application is the CPU is doing a quick switch to complete. This switch is random.

When the JVM starts, it starts multiple threads, and at least two threads can parse it out.

1, The thread that executes the main function,

The thread's task code is defined in the main function.

2, the thread responsible for garbage collection.

The end of the main thread is the wrong idea for the JVM to end. There are other threads in progress, all threads end, andtheJVM ends.

The CPU can only run one thread at a time in the computer, but he keeps switching quickly across multiple threads, letting people feel that multiple threads can run concurrently.

How do I create a thread?

Create thread mode One: Inherit the thread class.

Steps:

1, define a class that inherits the Thread class.

2, overwrite the run method in the Thread class .

3, create a thread for the subclass object thatdirectly creates the thread .

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

You can get the name thread- number of the thread through the getName of thread ( from 0 Start )

(When the thread object is created, it is numbered and the thread has been created, but the thread has not started running)

The main thread's name is main.

The purpose of creating a thread is to open an execution path and run the specified code and other code to run concurrently.

The specified code that runs is the task of this execution path.

The tasks of the main thread created by the JVM are defined in the main function.

and the custom thread where is its task?

The thread class is used to describe threads, which require tasks. So the Thread class also describes the task.

This task is represented by the run method in the Thread class . That is, therun method is the function that encapsulates the custom thread that runs the task.

defined in the Run method is the task code that the thread will run.

The thread is turned on in order to run the specified code, so only the thread class is inherited and the run method is replicated .

Define the running code in the run method.

If the line changes to d1.run (), Although there is a thread, the JVM considers him as a normal run Method execution, only one main thread, and does not run multi-threading, changed to D1.start () after the multithreading began to run


Thread.CurrentThread ()--->> current thread


There is only one column in the stack memory, after multiple threads, there are several columns

JAVA_DAY13 multithreading

CPU Execution Eligibility: can be processed by the CPU , queued in the processing queue

CPU execution: Being processed by the CPU


The first way to create a thread : inherit the thread class.

<pre name= "code" class= "CPP" > First Method Principle: Class Thread//thread source code content {private Runnable R; Thread () {   //no parameter constructor}thread (Runnable R) {//Parameter constructor THIS.R  = r;} public void Run () {//create if (r!=null) R.run ();} public void Start () {//thread start run ();}} Class Subthread extends thread{   //The first method inherits Threadpublic void Run () {System.out.println ("Hahah");}} {  //main function content subthread s = new Subthread ();  Create a thread class object without parameters S.start ();}


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

1, defines the class implementation Runnable interface.

2, overwrite the Run method in the interface , encapsulating the thread's task code into the run method.

3, The thread object is created through the thread class and the subclass object of the Runnable interface is used as the thread The parameters of the constructor for the class are passed.

Why? Because the threads ' tasks are encapsulated in the Run method of the Runnable Interface Subclass Object .

Therefore, when you create a thread object, you must explicitly define the task that you want to run.

4, call the Thread object's start method to open the thread.

Package Day12;class Demo2 implements Runnable//prepare to extend the functionality of the demo class so that its contents can be executed as a thread's task. Completed via an interface. {public void Run () {Show ();} public void Show () {for (int x = 0; x <; + x + +) {System.out.println (Thread.CurrentThread (). GetName () + "... }}public class Threaddemo {public static void main (string[] args) {Demo2 d = new Demo2 (); thread T1 = new Thread (d);//If it is new thread (); Thread will run his own thread, not our D threads thread t2 = new Thread (d); T1.start (); T2.start ();}}

the principle of the second method and the first method

Class Thread//thread source code content {private Runnable R; Thread () {   //no parameter constructor}thread (Runnable R) {//Parameter constructor THIS.R  = r;} public void Run () {//create if (r!=null) R.run ();} public void Start () {//thread start run ();}} Class Threadimpl implements Runnable{public void Run () {System.out.println ("Runnable Run");}} {    //main main function content Threadimpl i = new Threadimpl (); Thread t = new thread (i);//Threadt.start with reference ();}

. the benefits of the second approach

Runnable

is a way to encapsulate a thread task

Benefits of implementing the Runnable interface:

1, the task of the thread is separated from the subclass of the thread and carried out in a separate package.

Encapsulates a task into an object based on object-oriented thinking.

2, avoids The limitations of Java single inheritance.

Therefore, the second way to create threads is more common.

Limitations of the first kind:

If the class itself is a Zi Subclass, has inherited the parent class Fu, and then inherits the Thread into multiple inheritance, this is the JAVA not allowed, so the first method has limitations.

. Buy Ticket system

.13- Multithreading ( The phenomenon of thread safety issues )

.14- Multithreading ( causes of thread safety issues )

Causes of thread safety problems:

1, multiple threads are manipulating the shared data.

2, there are multiple threads for manipulating shared data.

When a thread executes multiple code processes that share data, other threads participate in the operation.

Causes a thread-safety problem to occur.

.15- Multithreading ( Synchronous code block )(lock sync Lock)

Solve the idea;

is to encapsulate the thread code that has multiple operations sharing data, and when the threads execute the code,

Other threads are not allowed to participate in the operation.

It is necessary for the other threads to participate in the operation when the code is executed by the front-end thread.

In Java , this problem can be solved by synchronizing blocks of code.

Format of the synchronized code block:

Synchronized ( object ) any object, but be sure to have a

{

Code that needs to be synchronized;

}

Class Ticket implements runnable//extends thread{private  int num = 100;object obj = new Object ();p ublic void Run () {WHI Le (True) {synchronized (obj) {if (num>0) {try{thread.sleep (10);} catch (Interruptedexception e) {}system.out.println (Thread.CurrentThread (). GetName () + ".... Sale ...." +num--);}}}}

Benefits of synchronization: resolves thread security issues.

The disadvantage of synchronization: the relative reduction of efficiency, because the synchronization of the outside of the thread will judge the synchronization lock.

the premise of synchronization: There must be multiple threads in the synchronization and use the same lock.

. Sync Function

Public synchronized void Add (int num)//synchronous function {sum = sum + num;try{thread.sleep (10);} catch (Interruptedexception e) {}system.out.println ("sum=" +sum);

The lock for the synchronization function is this

The difference between a synchronization function and a synchronous code block:

The lock of the synchronization function is a fixed this.

The lock of the synchronization code block is any object.

It is recommended that you use synchronous code blocks. Because the lock is fixed with this, there is no flexibility.

. 20- Multithreading ( Verifying the lock of a static sync function )

A static synchronization function uses a lock that is the byte-code file object that the function belongs to

Can be obtained using the GetClass method, or it can be represented by the current class name . class.

Single-instance mode under multiple threads

See my blog http://blog.csdn.net/qq_24653023/article/details/51706972

JAVA_DAY14 multithreading

Wait / wake mechanism.

The method involved:

1,Wait (): causes the thread to freeze, and the wait thread is stored in the thread pool.

2,notify (): wakes a thread in the thread pool ( any ).

3,notifyall (): wakes all threads in the thread pool.


All of these methods must be defined in synchronization.

Because these methods are the methods used to manipulate the thread state.

It is important to be clear on which locked thread the operation is.


Why is the method for manipulating Threads wait notify Notifyall defined in the Object class?

Because these methods are the methods of the monitor. A monitor is actually a lock.

A lock can be any object, and the way an arbitrary object is called must be defined in the object class.

Notify: only one thread can be awakened, if this party wakes up the party, it is meaningless. And while Judging the token +notify will cause a deadlock.

Notifyall resolves an issue in which the thread of this party will surely wake the other thread.

Bi Xiangdong Java Video Learning note "DAY11-DAY13 multithreading"

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.