Some understanding of Java threading

Source: Internet
Author: User

process: A running program that allocates memory to allow the application to run

Windows systems are multi-tasking (multiple applications can be run concurrently)

Macro view: Windows does allow multiple programs

Microscopic view: The CPU quickly switch to perform tasks, because of the speed is particularly fast, we do not feel the process of switching

Threads: threads are responsible for the execution of code in a process, which is the execution path in a process

Question: No learning thread, why code can execute

When the Java program is running, the JVM will help us create a main thread to execute the code. The main thread is responsible for the code execution in the main method.

There are at least 2 threads in a Java program:

One is the main thread responsible for the code execution in the main method, a garbage collection station thread, responsible for garbage collection

Multithreading: Multiple threads in a process perform different tasks at the same time. "At the same time": the single core CPU quickly switch multi-threaded execution task, speed particularly fast, feel no switch

Benefits of Multithreading:

1. Resolve a problem that performs multiple tasks concurrently in a process

2. Increase the utilization of resources

Disadvantages of Multithreading:

1. Increase the burden on the CPU, not the more threads the better

2. Reduces the execution probability of a thread in a process

3. Threads are prone to thread-safety issues

4. Deadlock-prone phenomenon

There are two ways to create threads in Java:
Way One: Thread (Threading Class)

1. You need to define a class to inherit the thread class

2. Rewrite the Run method in the thread class to write the task code of the custom thread in the Run method

Each thread has its own task code, and the task code of the main thread created by the JVM is the main method, and the task code of the custom thread is written in the Run method

3. Create a subclass of thread and call the Start method to open the thread

Note: Once the thread is turned on, the Run method in the thread object is executed by default, but do not call the Run method directly, if calling the Run method directly is no different from the normal method.

The life cycle of a thread:

Create: A new Thread object was created.

Run: After the thread object is created, other threads call the object's start () method. The state of the thread is located in a pool of running threads, which becomes operational and waits for the CPU to execute.

Run: The ready state of the thread gets the CPU execution and executes the program code.

Block temporary plug: The blocking state is that the thread abandons the CPU for some reason and temporarily stops running. Until the thread is in a ready state, the opportunity to go to the running state is reached.

Death: When a thread finishes its task.

Common methods in Threads:

Thread (String name) The name of the initial thread

Getnema () returns the name of the thread

Setnema (String name) to set the thread object name

Sleep () thread sleeps for a specified number of milliseconds

GetPriority () returns the priority of the current object the priority of the default thread is 5

setpriority (int newpriority) Sets the priority of the thread although it is set to priority, but the specific implementation depends on the implementation of the underlying operating system (the highest priority is 10, the smallest is 1, the default is 5)

CurrentThread () Returns the object of the thread being executed by the Cup

Workaround for thread Insecurity:
Java To line Cheng:

Mode one: Synchronizing code blocks

The lock object can be any object in Java (any type of object)

Any object in Java will have the state of an object, which can be used as an identifier for the lock by its state.

Column such as: statue = 0 means lock off statue=1 means open

Synchronized (Lock object) {}

Note Points for using synchronous code blocks:

1. Any object can be a lock object

2. If you call the Sleep method in a synchronized code block, the lock object is not released

3. Synchronous code blocks are required only if there is a real thread safety

Failure to do so will reduce execution efficiency

4. Multi-threaded Operation lock object must be unique, otherwise invalid

Don't know when the thread is safe when it's not safe?

the root cause of thread safety problems:

1. There are two or more than two threads, and a resource is shared between threads

2. Multiple statement operations shared resources

Mode two: synchronization function: synchronized modifier function with keyword

A synchronization function is a lock object.
The use of a synchronous function is a point of note for a static function:

1. As a non-static function, the lock of the synchronous function is the object that invokes the method (the This object), and if it is a static synchronization function, the lock object is the byte-code file of the class to which the current function belongs (class object)

2. The lock object of the synchronization function is fixed and cannot be specified by itself

3. The synchronization function is the code that synchronizes the entire function

Synchronizing code blocks and synchronization functions, using synchronous blocks of code preferentially

Reason:

1. The lock object of the synchronization code block can be arbitrarily specified by me, the synchronization function is fixed

2. Synchronization code block can control the synchronization scope, the synchronization function must be the entire function of all the code is synchronized

Thread Deadlock behavior:

Thread deadlocks do not necessarily occur and may occur

How to solve the deadlock phenomenon: no plan, try to avoid

Threads are defined in two ways:

1. Customize an implementation runable interface that provides a run method in the interface

2. Implement the Run method in the Runable interface to write the tasks in the thread in the Run method

3. Create an implementation object for the Runable interface

4. Create a thread object and take the object created by the Runable implementation class as a parameter

5. Call the star method of the tread object to open the thread

Question: Why should I pass an object of the Runable interface implementation class as a parameter?

In order for the Run method in the object to be executed in the Run method in the thread, the Run method in this object can be executed as a task in the threads

Methods thread and Runable recommend the use of runable

Java is a single inheritance, it is not possible to inherit thread objects to implement multithreading

thread communication: One thread completes its task, notifies another thread to complete another task

Wait (); Wait if the thread executes the wait method, the thread will be in a wait state, and the waiting state's thread must call the Notify () method through another thread to wake

Notify (); Wake up a thread in a random wake thread pool

Notifyall (); Wake up all the threads

The use of wait and notify note points:

The 1.wait method and the Notify method are the object objects

The 2.wait method and the Notify method must be executed in the synchronization thread

The 3.wait method and the Notify method must have a lock object to invoke

Some understanding of Java threading

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.