Threads and Locks

Source: Internet
Author: User
Tags finally block instance method thread class

Processes & Threads
    • Process
      Each process has its own code and data space (process context), and there is a significant overhead of switching between processes, with a process containing 1--n threads. (Process is the smallest unit of resource allocation)
    • Thread
      The same class of threads share code and data space, each thread has a separate run stack and program counter (PC), and thread switching overhead is small. (Thread is the smallest unit of CPU scheduling)

PS: A thread is a program of multiple execution paths, executing a dispatch unit, depending on the process existence. The thread can not only share the memory of the process, but also have a memory space of its own, which is also called the line stacks, which is allocated by the system when the thread is created, primarily to hold the data used internally by the thread, such as variables defined in the thread execution function.
Note: Multithreading in Java is a preemption mechanism rather than a time-sharing mechanism. Preemption refers to having multiple threads in a running state, but only one thread is allowed to run, and they preempt the CPU in a competitive way.

Reference: http://www.cnblogs.com/DreamSea/archive/2012/01/11/JavaThread.html

Create thread mode
    1. Inherit the Thread class;
    2. Implement Runnable interface;
    3. Implementing the Callable Interface (1.5)
    4. Thread pool
    • Start & Run
      Note: Instead of executing multithreaded code immediately after the call to the start () method, the thread becomes a running state (Runnable) and when it is run is determined by the operating system.
      Start the thread with the start () method, which really implements multi-threaded operation; the run () method is called the thread body, and the Run () method alone is called as a normal method.
Thread Status & Life cycle
    • NEW: After creating a Thread object (not alive)
    • Ready (Runnable): After the start () method call (Alive)
    • Running (Running): Run () method (alive)
    • Blocking (Blocked): Thread discards the use of the CPU. When a thread enters a blocking state, it cannot enter the queued queue. A thread can be turned into a ready state only if the cause of the blocking is eliminated (alive)
    • Death (Dead): Executes the task (run end) or throws an exception (not alive). (A run-time exception occurs when the Start method is called for a thread in the dead State)
      Java Thread status keyword: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED .
Thread method
    • Sleep ()
      Pause for a period of time, blocking state (interruptible, no release lock)
    • Yield ()
      The current thread gives up CPU control to allow other ready-state threads to run (toggle); the yield () method will not work if there are no equal priority threads (no release lock)
    • Join ()
      Merges a thread. Call Other.join () in one thread and wait for other to finish before continuing with this thread (interruptible)
    • Interrupt ()
      You can only break a thread that is in a blocked state, and you cannot break a running thread.
Object method
    • Wait ()
      Wait, release the lock. (Can be interrupted)
      If the object calls the wait method, it causes the thread holding the object to hand over the object's control and then waits.
    • Notify ()
      Wakes up a thread that is waiting for the object monitor.
      If an object calls the Notify method, it notifies a thread that is waiting for control of the object to continue running.
    • Notifyall ()
      Wakes all threads that are waiting for the object monitor.
      If the object calls the Notifyall method, all threads waiting for control of the object will be notified to continue running.

    • At any one time, the object's control (monitor) can only be owned by one thread.
    • Whether you are executing the wait, notify, or Notifyall method of an object, you must ensure that the currently running thread obtains control of the object (monitor).
    • If the above three methods of the object are executed in a thread without control, the java.lang.IllegalMonitorStateException exception is reported.
    • The JVM is multi-threaded and, by default, does not guarantee the timing of runtime threads.

There are three ways that threads gain control:

    • Executes a synchronous instance method of an object.
    • Executes a synchronous static method of the object's corresponding class.
    • Executes a synchronization block that adds a synchronous lock to the object.

"Object method" reference: http://longdick.iteye.com/blog/453615

Thread safety: Often used to depict a piece of code. In the case of concurrency, the code is multithreaded and the scheduling order of the threads does not affect any results
Synchronization: Synchronization in Java refers to the use of human control and scheduling, to ensure that multi-threaded access to shared resources become thread-safe, to ensure the accuracy of the results.

Synchronized keyword: Locks the current object when a method is specified.

Synchronized & Lock
    • Lock is an interface, and synchronized is a keyword in Java, synchronized is a built-in language implementation;
    • Synchronized in the event of an exception, the lock is automatically released by the thread, and therefore does not cause a deadlock, and lock is most likely to cause a deadlock if it fails to release the lock voluntarily through unlock () when an exception occurs. Therefore, lock must be released in the finally block when using lock;
    • Lock allows the thread that waits for the lock to respond to interrupts, while synchronized does not, and when the synchronized is used, the waiting thread waits and fails to respond to interrupts;
    • Lock can be used to know if there is a successful acquisition of locks, and synchronized is unable to do so.
    • Lock can improve the efficiency of multiple threads for read operations.

      Reference: http://www.cnblogs.com/dolphin0520/p/3923167.html

Lock more flexible, you can freely define the locking unlock order of multiple locks (synchronized to follow the order of the first addition)
A variety of locking schemes are available, lock-blocking, Trylock-free, lockinterruptily-break, and Trylock with a time-out version.
Essentially the monitor lock (i.e. synchronized is the same)
And the combination of the condition class.

Non-static synchronized and static synchronized are not mutually exclusive.

Classification of Locks
    • Can be re-entered lock
      If the lock is reentrant, it is referred to as a reentrant lock.
      Like synchronized and Reentrantlock are reentrant locks, reentrant. In my opinion, it actually shows the allocation mechanism of locks: thread-based allocation rather than method-invocation-based allocations.
    • Interruptible Lock
      is a lock that can be broken accordingly.
    • Fair lock
      A fair lock is to obtain the lock in the order in which the lock is requested. For example, there are multiple threads waiting for a lock, and when the lock is released, the thread that waits the longest (the first requested thread) gets the one, and this is the fair lock.
      An unfair lock does not guarantee that locks are obtained in the order in which they are requested. This can cause some or some threads to never get locks.
      In Java, synchronized is a non-fair lock that does not guarantee the order in which the waiting thread acquires the lock.
      For Reentrantlock and Reentrantreadwritelock, it is a non-fair lock by default, but can be set to a fair lock.
Thread pool

If the number of concurrent threads is large, and each thread is executing a short task, then the frequent creation of threads can greatly reduce the efficiency of the system because it takes time to create threads and destroy threads frequently.

    • Threadpoolexecutor class

Thread initialization in the thread pool:
After the thread pool has been created, by default, there are no threads in the thread pools, but wait for a task to come before creating the thread to perform the task unless the prestartallcorethreads () or Prestartcorethread () method is called

    1. If the number of threads in the current thread pool is less than corepoolsize, then each task will create a thread to perform the task;
    2. If the number of threads in the current thread pool is >=corepoolsize, each task will attempt to add it to the task cache queue, and if added succeeds, the task waits for the idle thread to take it out, or if the add fails (typically, the task cache queue is full). Will attempt to create a new thread to perform this task;
    3. If the number of threads in the current thread pool reaches maximumpoolsize, a task rejection policy is taken to handle it;
    4. If the number of threads in the thread pool is greater than corepoolsize, if a thread is idle for more than KeepAliveTime, the thread is terminated until the number of threads in the thread pool is not greater than corepoolsize, and if the threads in the core pool are allowed to set the time to live, If the thread in the core pool is idle longer than KeepAliveTime, the thread is terminated.

Reference:
Http://www.cnblogs.com/dolphin0520/p/3932921.html
Https://www.cnblogs.com/wxd0108/p/5479442.html
Http://www.jianshu.com/p/40d4c7aebd66

Threads and Locks

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.