Dark Horse programmer--java Learning Note six (multithreading)

Source: Internet
Author: User

1, what is multithreading? A program can perform multiple tasks, each of which is called a thread, and a program that runs multiple threads is called a multithreaded program.
Process: A program that is in progress (literal translation).
Thread: A control unit (execution path) in the process that is responsible for program execution.
Multithreading Benefits: Solves the problem of multi-part code running at the same time.
The disadvantage of multithreading: too many threads can lead to reduced efficiency.
In fact, the simultaneous execution of multiple applications is done by the CPU in a fast switchover. This switch is random. CPU switching takes time, resulting in reduced efficiency
2, create thread mode:
Create thread mode One: Inherit the thread class
1. Define a class to inherit the thread class.
2. Override the Run method in the thread class.
3. Create a thread for the subclass object that directly creates the thread.
4. Call the Start method to open the thread and invoke the thread's task run method execution.
The purpose of creating a thread is to open an execution path that runs the specified code and other code implementations at the same time, and the specified code that runs is the task of the 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 has a description of the task. This task is represented by the Run method in the thread class. That is, the Run method is a function that encapsulates a custom thread to run a task, and the Run method defines the task code that the thread will run.
The thread is opened to run the specified code, so only inherit the thread class and copy the Run method to define the running code in the Run method.
Create thread mode Two: Implement the Runnble interface.
1, the definition class implements the Runnable interface.
2. Overwrite the Run method in the interface to encapsulate the thread's task code in the Run method.
3. The thread object is created through the thread class and the subclass object of the Runnable interface is passed as a parameter to the constructor of the thread class.
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 Start method of the thread object to create a new thread.
Benefits of implementing the Runnable interface:
1, the task of the thread is separated from the subclass of the thread, carried out in a separate package, according to the object-oriented thinking of the task encapsulated into objects.
2, avoids the limitations of Java single inheritance. Therefore, the second way to create threads is more common.
The thread class, runnable interface internal source code relationship simulation codes:
Class thread{
Private Runnable R;
Thread () {
}
Thread (Runnable R) {
THIS.R = R;
}
public void Run () {
if (R!=null)
R.run ();
}
public void Start () {
Run ();
}
}
If you need to have a lot of tasks, the cost of creating a separate thread for each task is too high, so consider the thread pool.
Thread state: There are 6 kinds of getstate that can be called to get the state of a thread.
CPU execution Eligibility: can be processed by the CPU and queued in the processing queue.
CPU execution: Being processed by the CPU.
Once the Start method is called, the thread is in a running state and may or may not be running, depending on when the operating system gives the thread the time to run.
Preemptive scheduling: The operating system gives each task a time slice to perform the task. After the time slice is exhausted, the operating system deprives the thread of running power and gives the opportunity to another thread, and the operating system considers the thread's priority (Min_priority max_priority, norm_priority).
Collaborative scheduling: A thread friend loses control only when it calls the yield method, or when it is blocked or waiting.
If the number of threads is more than the number of processors, the time slice will be the same.
3, the thread terminates when the thread's Run method executes the last statement in the method body and returns by executing a return statement, or when there is an exception that is not caught in the method. In earlier versions of Java, a stop method could be used, but it has now been deprecated.
There is a way to force a thread to terminate, and the interrupt state of the thread is set. Each thread has a Boolean flag, and each thread should check the flag periodically to determine if the thread has been interrupted.
while (! Thead.currentthread (). isinterrupted () &&more work to do) {
Do + work
}
If the thread is blocked, the interrupt state cannot be detected, so a Interruptedexception exception is thrown.
public void Run () {
try {
...
While (more work to do) {
Do + work
Thread.Sleep (delay);
}
}
catch (Interruptexception e) {
Thread was interrupted during sleep
}
finaly {
Cleanup if required
}
Exiting the Run method terminates the thread
}
Interrupted is a class method that clears the interrupt state. On the other hand, isinterrupted is an instance method and does not clear the interrupt state.
4, thread synchronization, in most real-world multithreaded applications, two or more than two threads need to share access to unified data. This can result in inconsistent data. This situation is called competitive conditions. How to prevent code blocks from being disturbed by concurrent access. Java provides the Synchronized keyword for this purpose, and introduces the Reentrantlock class in Java5.
The difference between a synchronization function and a synchronous code block:
1, the synchronization function of the lock is fixed this.
2. The lock of the synchronous code block is any object.
It is recommended that you use synchronous code blocks.
Because the lock of the synchronization function is fixed this, the lock of the synchronous code block is arbitrary object, then if both the synchronous function and the synchronous code block use this as the lock, the synchronization can be implemented
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.
methods involved in the wait/wake mechanism:
①wait (): The thread is frozen and the wait thread is stored in the thread pool.
②notify (): Wakes up a thread in the thread pool (any one is possible).
③notifyall (): Wakes all threads in the thread pool.
P.S.
1, these methods must be defined in synchronization, because these methods are used to manipulate the thread state.
2, must be clear in the end of the operation is which locked thread!
3, wait and sleep difference?
①wait can specify time or not. Sleep must specify a time.
② in synchronization, the CPU execution and lock processing are different.
wait: Release the execution and release the lock.
sleep: Releases the execution and does not release the lock.
The method of how to manipulate threads wait, notify, notifyall are defined in the object class, because these methods are the methods of the monitor, and the monitor is actually a lock.
A lock can be any object, and any object invocation must be in the object class.
The basic structure of Reentrantlock is as follows:
Mylock.lock ();
try {
Critial section;
}
finally {
Mylock.lock ();
Locks are reentrant, keeping a count to keep track of nested calls to the lock method. Each invocation of a thread uses the same method of locking. To be aware of the code in the critical section, do not throw an exception out of the critical section, causing the object to be damaged.
Conditional object: The thread usually enters the critical section, but discovers that it can execute after a certain condition is met. To use a conditional object to manage threads that have acquired a lock but cannot do useful work. is called a condition variable.
An object can have more than one related conditional object. Gets a conditional object using the Newcondition method.
Lock interface: A synchronous code block or a synchronization function appears instead, and the implicit operation of the synchronization becomes a display lock operation. At the same time more flexible, can be a lock plus multiple sets of monitors.
Lock (): Gets the lock.
Unlock (): Release the lock, in order to prevent the exception, so that the lock can not be closed, so the closing action of the lock should be put in finally.

Condition interface: The wait, notify, Notifyall methods appear instead of the object. These monitor methods are individually encapsulated and become condition monitor objects that can be combined with arbitrary locks.
The await method in the condition interface corresponds to the Wait method in object.
The signal method in the condition interface corresponds to the Notify method in object.
The Signalall method in the condition interface corresponds to the Notifyall method in object.

Dark Horse programmer--java Learning Note six (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.