Dark Horse programmer-java Basics-Multithreading

Source: Internet
Author: User
Tags ticket

First Lecture Multithreading Overview

1. Definition

process: is a program that is being executed. Each process execution has an execution order, which is an execution path, or a control unit. When the program runs, it is allocated a memory space, the process is used to identify the space, the package unit, the thread is the real part of the thread.

Thread: A separate control unit in a process that controls the execution of a process.

There is at least one thread in a process.

Example: Java JVM starts with a process java.exe. At least one thread in the process is responsible for the execution of the Java program, and the code that runs on the thread exists in the main method, which is called the main thread.

Description: The JVM started with more than one thread, and a thread responsible for the garbage collection mechanism.

2. Multithreading

Multithreading enables multiple code to "synchronize" execution. On the premise of a single core, multiple threads are getting the CPU execution right, and the CPU executes to whom and who runs. It needs to be clear that at some point there can be only one thread running.

Second lecture Create thread - Inherit tread class

1. Create thread the first way: Inherit the Tread class

Steps:

1) Define class inheritance tread class;

2) The Run method in the replication tread class;

3) Call the thread's start () method, which has two functions: Start the thread, call the Run method;

2. Run and Start method features

The thread class is used to describe threads, and the class defines a function that holds the code that the thread wants to run, which is the Run method. The main thread stores the running code in the Main method.

Purpose of the replication Run method: Store the custom code in the Run method and let the thread run.

3, Exercise: Create two threads, and the main thread alternately run

L Define thread class inheritance tread class

L Create two threads;

L start two threads;

The code is implemented as follows:

4. Thread Running state

The thread has the following 5 states in operation: Create, run, freeze, temporary state (blocked), die.

The relationships between these states are as follows:

5. The name of the thread in the virtual machine

Get Thread Name:

Gets the thread name format: Thread object. GetName ();

Threads have their own default name: thread-number, which starts with 0.

Set Thread Name:

The SetName () or constructor sets the thread name.

The constructor of the thread class and the name of the thread are set, so you can call the constructor of the thread class to set the names of the threads when you define the thread class.

The method CurrentThread () in the thread class can get to the currently running thread object.

gets and sets the meaning of the thread name: threads can be managed when there are many threads.

Third Speaking Create thread - implement Runnable interface

1, multiple window simultaneously sell the ticket example

Create multiple threads while performing a sell ticket function.

Using the inherited thread class method to create a thread, implement multiple windows to sell tickets at the same time, but the number of tickets must be defined as static, or there will be a multi-sell situation. Then, when we write code, we are less likely to define static variables, because static variables have a long life cycle that wastes resources.

Thus, the second way to create a thread is introduced: Implementing the Runnable Interface

2, the second way to create a thread--implementation of the Runnable interface

Steps:

1) Define class implementation runnable interface;

2) Cover the Run method in the Runnable interface;

Purpose: Store the code that the thread will run in the Run method.

3) The thread object is established through the thread class;

4) Pass the subclass object of the Runnable interface as the actual parameter to the constructor of the thread class;

To pass the subclass object of the Runnable interface to the constructor of the thread class.

Because: the object that the custom run method belongs to is the subclass object of the Runnable interface, so let the thread specify the run method of the specified object. That is, identify the object to which the Run method belongs.

5) Call the Start method of the thread class and open the thread, and invoke the Run method of the Runnable interface subclass;

The code is implemented as follows:

The benefits of the comparison of the implementation and inheritance methods :

L implementation can avoid the limitations of Java single inheritance, when defining a thread, it is recommended to use the implementation method;

L The resource is independent, solve the problem of multi-window selling ticket;--this ticket-selling process only creates a tick in memory, and multiple ticket-selling threads can only operate on this ticket resource.

Fourth Lecture Multithreading security issues

1, multithreading Security issues overview

The problem occurs because when multiple statements are working on the same thread to share data, one thread executes a portion of the multiple statements, does not finish, and is executed by another thread, resulting in an error sharing the data.

WORKAROUND: A statement that shares data on multiple operations can only be done by one thread to allow other threads to participate.

Workaround in Java: Synchronizing blocks of code

Synchronized (object)

{

Code that needs to be synchronized

}

Description: The object is like a lock, the thread holding the lock can execute in the synchronization, the thread that does not hold the lock even gets the CPU execution right, also cannot enter, because does not acquire the lock.

2. Simultaneous use

Prerequisites for synchronization: two or more than two threads must be used, and multiple threads must use the same lock.

The advantages of synchronization: solve the problem of multithreading security;

The disadvantage of synchronization: multiple threads need to determine the lock, more expensive resources;

3, the manifestation of synchronization

Synchronizing code blocks

code example:

Synchronization functions

4, the lock in sync

1) The lock of the synchronization code block can be any object;

2) The lock of the synchronous generation function is this (instance object of the class where the function is located);

3) The lock of the synchronous static function is the corresponding bytecode file object of the class, class name. class;

Fifth Lecture Application of synchronization in single-case design mode

1. Overview

There are two embodiments of the single-case design pattern: a hungry man and lazy.

Because lazy is the function is called when the object is created, and the creation of more than one statement of the object, so in multi-threading is prone to security problems.

2. Solving the lazy-type safety problem method

The function that gets the object is defined as synchronous, as follows:

However, each call to the function needs to determine the lock, affecting the efficiency of the operation, you can use the double judgment form to slightly improve the operating efficiency, as follows. In this way, you can reduce the number of locks, but the code is increasing.

3. Deadlock

Synchronization is nested synchronously, and the synchronization lock is not the same. and different threads are waiting for each other's locks.

Summary of Knowledge points

1. There are two ways to create a thread: inherit the thread class; Implement the Runnable interface

The realization of runnable interface can solve many problems, and also can separate resources to ensure the uniqueness of resources.

2, multi-threaded appearance makes many programs can run "at the same time", but there may be shared data errors, resulting in multi-threaded security issues, at this time, can be controlled by the synchronization mechanism, synchronization includes: Synchronous code block, synchronization function.

3. When using synchronous code blocks, the following questions need to be clarified:

1) make clear what code is multithreaded running code (the code in the Run method);

2) clear sharing of data;

3) Clear the multi-threaded running code which is the operation of shared data;

4, lazy-type synchronization problem

Lazy examples are lazy-loaded, and there are multiple action statements that may cause security problems in multithreaded situations. At this point can be used to control the synchronization function or synchronization code block, but each time the instance needs to determine the efficiency of the lock, we can double-judge the way to reduce the number of locks, thereby slightly improving the efficiency of the operation. However, in the actual application process, we recommend the use of a hungry man type.

Dark Horse programmer-java Basics-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.