Threads-Consolidate multiple articles

Source: Internet
Author: User

Reference resources: http://www.mamicode.com/info-detail-517008.html

One, process, thread differences

Process: Each process has independent code and data space, process switching can be very expensive, a process contains 1~n threads

Threads: Shared code and data space for the same thread, with separate run stacks and program counters for each thread, and low thread switching overhead

There are five stages: Create, ready, run, block, terminate.

Multi-process: The operating system can run multiple tasks

Multithreading: Multiple sequential streams in the same program are executing.

Two, the difference between thread and runable

1. If a class inherits thread, it is not suitable for resource sharing

Implement the Runable interface, it is easy to realize the resource sharing

Suitable for multiple identical program code to handle the same resource

2. Avoids the restriction of single inheritance in Java

3. Increase the robustness of the program, the code can be shared by multiple threads, code and data Independent

Third, Note: In Java, each program runs at least 2 threads, main garbage collection thread

Whenever a class is executed with a Java command, a JVM is started, and each JVM starts a process in the operating system.

Iv. Comparison of threading methods

Sleep () and yield ()

Sleep (long Millis) lets the thread hibernate within the specified number of milliseconds

Yield () pauses the currently executing thread object and executes other threads

Operational status----> Operational status

Let the current thread go back to the operational state to run another thread with the same priority to get the opportunity to run properly between threads of the same priority, and in practice there is no guarantee that yield () will reach the concession (the compromised thread may be re-selected by the thread scheduler)

Sleep () causes the current thread to go to a standstill, and the thread that executes sleep () will not be executed for a specified period of time;

Yield () simply returns the current thread back to the executable state, and the thread executing yield () is likely to be executed immediately after entering the executable state.

The Sleep method allows the currently running thread to sleep for a period of time, entering a non-operational state, which is set by the program,

The yield method gives the current thread the CPU possession, but the time to make it out is not settable.

In fact, the yield () method corresponds to the following actions: first detect whether the thread with the same priority is in the same operational state, and if so, hand over the CPU's possession to this thread, or continue running the original thread. So the yield () method is called "concession," which gives the opportunity to other threads of equal priority.

The Sleep method allows a lower-priority thread to get a running opportunity,

When the yield () method executes, the current thread is still in a running state, so it is not possible to let the lower-priority threads get CPU possession.

In a running system, if a higher-priority thread does not call the sleep method and is not blocked by i\o, the lower-priority thread can only wait for all higher-priority threads to run to the end before the opportunity runs.

Wait and sleep differences
Common denominator:

1. They are all in multi-threaded environment, can block the number of milliseconds specified at the call of the program, and return.
2. Wait () and sleep () can break the thread's suspend state through the interrupt () method, causing the thread to throw interruptedexception immediately.
If thread A wants to end thread B immediately, you can call the interrupt method on the thread instance that corresponds to threads B. If thread B is wait/sleep/join at the moment, thread B will immediately throw interruptedexception, and return directly in catch () {} to safely end the thread.
It is important to note that Interruptedexception is thrown from within the thread itself, not by the interrupt () method. When you call interrupt () on a thread, the thread does not throw interruptedexception at all if it is executing normal code. However, once the thread has entered wait ()/sleep ()/join (), the interruptedexception is immediately thrown.
different points:
1. Method of the Thread class: sleep (), yield (), etc.
Method of object: Wait () and notify (), etc.
2. Each object has a lock to control synchronous access. The Synchronized keyword can interact with the object's lock to achieve thread synchronization.
The sleep method does not release the lock, and the wait method frees the lock so that other threads can use the synchronization control block or method.
3. Wait,notify and Notifyall can only be used in a synchronous control method or in a sync control block, and sleep can be used anywhere
4. Sleep must catch exceptions, while wait,notify and notifyall do not need to catch exceptions
So the biggest difference between the sleep () and wait () methods is:
Sleep () when sleeping, keep the object lock, still occupy the lock;
While wait () sleeps, the object lock is released.
But wait () and sleep () can break the thread's suspend state through the interrupt () method, causing the thread to throw interruptedexception immediately (but not recommended).

Join () waits for the thread to terminate (the thread that called this method ends before other threads can execute)

Interrupt () interrupts a thread (if the thread has opened a resource and has not closed the/run method has not finished enforcing the end thread, causing the resource to fail to close)

Five, thread synchronization

1.sychronized

1) is within an object instance, synchronized Amethod () {} can prevent multiple threads from accessing the object's synchronized method at the same time (if an object has multiple synchronized methods, As long as a thread accesses one of the synchronized methods, the other thread cannot access any of the synchronized methods in the object at the same time. At this point, the synchronized method of the different object instances is not interfering. In other words, other threads can access the Synchronized method in another object instance of the same class at the same time;
2) is the scope of a class, synchronized static astaticmethod{} prevents multiple threads from accessing the synchronized static method in this class at the same time. It can work on all object instances of the class.

2, in addition to the method before using the Synchronized keyword, the synchronized keyword can also be used in a block in the method, indicating that only the resources of this block to implement mutually exclusive access. The usage is: synchronized (this) {/* block */}, which is scoped to the current object;

3, synchronized keyword is not inherited, that is, the method of the base class synchronized F () {} is not automatically synchronized F () {} in the inheriting class, but instead becomes F () {}. Inheriting a class requires that you explicitly specify one of its methods as the Synchronized method;

A Regardless of whether the Synchronized keyword is added to a method or an object, the lock it obtains is an object, not a piece of code or function as a lock-and the synchronization method is likely to be accessed by other threads ' objects.

B Each object has only one lock (lock) associated with it.

C The implementation of synchronization is a big cost to the system, and may even cause deadlocks, so try to avoid unnecessary synchronization control.

Threads-Consolidate multiple articles

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.