Basics of concurrent programming - a

I began to summarize knowledge about aspects of concurrency, first with a few blog to summarize the basic knowledge of concurrent programming, after then to read the source code and analysis.

Threads and processes

A thread is a process execution unit may also scheduling entity within the processes, threads, and processes are the following differences:

  • Address space : an execution unit processes within the process has at least one thread, they share the process address space, each process has its own separate address space
  • Resources have : the process of resource allocation and ownership of units, the same process threads share the process resources.

Process is the basic unit of resource allocation and scheduling system, the thread is a path of execution process, a process in which at least one thread, the process of resource shared by multiple threads process.

Thread creation and implementation

  • Thread class inheritance override the run () method
  • Implement Runnable run () method
  • Use Callable

The first two will not repeat them here, to emphasize that after the call start method, the thread does not start immediately, but in a ready state, after waiting for cpu resources will get into operation. The first two methods are no return value, we look for the third here, rewritten call () method by implementing Callable interface where you can specify the return value by specifying a generic type.

Thread and wait for notification

Object class is the parent of all classes, let's recall what it has among the method. Are hashCode (), notify (), notifyAll (), equals (), finalize (), getCalss (), clone (), toString (), wait (), wait (long timeout), wait (long timeout, int nanos) . Let's look at part of the method in which, first of all look at wait.

wait()

Internal wait () method is called wait (0), i.e. with the above parameters wait () method. Meaning wait forever to go after, wait method is called shared variables, the calling thread is blocked pending until the following situations occur will return:

  • Other thread calls notify or notifyAll method of shared objects
  • Other thread calls the interrupt method of this thread, the thread throws InterruptedException exception return

Note that, in the former method call wait to get a lock first shared object, otherwise thrown back illegalMonitorException an exception .

wait(long timeout)

And wait with parameters (long timeout) method blocks the pending timeout after time, automatic wake up his wake here refers to wake up after its shared resources have added to the competition to lock.

wait(long timeout,int nanos)

This method is nanos is within a given range, 1 <nanos <999999, timeout will be between ++ and call continues to wait (timeout) Operation

Another point to note is blocked by a suspended thread if not notify, notifyAll or is interrupted, wait a timeout operation, directly from a suspended state program ready state, this is called a false wake. For false wake, we have to wait method in a while loop, non-stop to test the thread was awakened conditions are satisfied, not satisfied then continue to wait, rather than using a simple if.

wait method will only release the lock is currently shared variables obtained, the other shared variables locks held by the current thread will not be released.

notify()

After a thread calls the shared object notify () method will be a wake-up call on the shared variable is suspended after a wait of thread, a shared variables may have on multiple threads waiting to acquire the lock, all awakened thread is random. After waking up, not immediately get into the lock of the shared object, but to continue to compete with other waiting threads . And wai same, only to get a lock on the shared object can call the notify () method, otherwise it will throw an exception IllegalMonitorStateException.

notifyAll()

notifyAll () method can wake up all threads waiting for a shared resource lock, call notifyAll method on shared variables before calling this method will only wake up call to the wait family of functions to be placed inside a set of shared variables waiting thread, if the method calls notifyAll then there is a thread calls the wait method of the covariates, it is not to be awakened. thread before calling the method notifyAll will wake up .

join()

join with no parameters and returns a void value method is a method of the Thread class, it is to wait after a call to join the back thread. That will be blocked after thread A call join method thread B , has been returned after thread B after executing the thread A before proceeding. If at this time, another thread calls interrupt thread A () method, thread A throws InterruptedException return.

Big Box  basic knowledge of programming concurrency - a eep "> sleep

sleep is also a method of the Thread class, when a thread execution method called sleep, he will let out within a specified time cpu occupancy rights, which is not involved in this period cpu scheduling, but different sleep and wait Shi, sleep and does not release the resources they occupied, such as locks occupied. After the time to sleep, and return back to normal, the thread is ready to compete again cpu resources . Similarly, during sleep, call interrupt () method throws an exception InteruptedException.

yield()

Let's look at the method a Thread class, yield () method can make their own occupied cpu, after calling the yield method, the thread is in the ready state, then the thread scheduler will get ready from the thread queue a thread with the highest priority thread, of course, there may be just the right thread to the execution proceed .

Thread interrupts

Let's look at the above thread has been mentioned interrupt, the interrupt thread is a collaborative model between threads, interrupt flag is set by the thread does not terminate the direct execution of the thread, but the interrupted thread interrupt processing according to their own state. In the wait, join, sleep state we mentioned above, the call interrupt () method will be abnormal . About thread interrupts us look at three methods:

  • void interrupt (): interrupt thread, when the thread A running thread B can call interrupt thread A () method to set the thread A interrupt flag is true and returns immediately. Setting a flag just sets the flag, the actual A thread has not been interrupted, it will continue down the implementation.
  • boolean isInterrupted (): detects whether the current thread has been interrupted, if the return is true, otherwise false.
  • boolean interrupted (): detects whether the current thread has been interrupted, if it returns true, otherwise false. And isInturrupted difference is that this method if you find current thread is interrupted, it will clear the interrupt flag. Here's a pit: in the interrupted () Gets the internal interrupt flag is currently calling thread rather than call interrupted () interrupt flag instance of an object method.

Thread context switching

Multi-threaded programming, the number of threads is generally greater than the number of cpu, cpu and every moment, only one thread to use. In order to make users feel more threads are performed simultaneously, cpu resource allocation using a round-robin algorithm, cpu assigned to each thread a time slice, the thread to perform tasks in the occupied cpu time slice, after completion of execution threads will let the right to use the cpu to other threads that he is in a ready state, this is the thread context switching.

The timing of the thread context switching are:

  • The current thread cpu time slice used up in a ready state
  • The current thread is interrupted when another thread

Deadlock

Deadlock refers to the phenomenon of two or more threads in the implementation process, due to competition for resources with each other out due to waiting for each other. This is our commonplace in the operating system topic, we look back, resulting in a deadlock four reasons:

  • Mutually exclusive conditions : that thread has acquired the exclusive protection of the resources that the resource at the same time only one thread occupy, at this time if there are other threads to request and obtain the resource, the requestor can only wait until the possession of resources thread releases the resource.
  • Request and hold : that thread has been at least one resource, but also proposed a new resource request, but the new resources have been other new thread possession, so the current thread is blocked, but blocked at the same time they have not released available resources
  • Inalienable condition : that the thread acquired resources can not be preempted before other threads are finished using their own, only to release the resources by themselves after themselves after use
  • Loop wait condition : that at the time of deadlock, there must be a thread - endless chain resources, i.e. thread {T0, T1, T2, T3 ... Tn} in T0 T1 is waiting for a resource occupied, T1 is waiting T2 resource ...... Tn is waiting for resources of T0.

So how to avoid deadlock it? Mutually exclusive conditions and inalienable conditions, is unlikely to be damaged, we want to avoid deadlock, just destroy request and hold or waiting for a loop condition in which one can be. For example two simple resources AB, thread 1 thread 2 AB acquisition order is the order of acquisition is BA, this deadlock occurs, we have to destroy the resource request sequence, we get the sequence to thread B AB, so the thread 2 thread 2 will awaken again to acquire the lock after the blocking occurs when the a's request, freed AB thread 1, so the perfect solution to the deadlock.

Daemon threads and user threads

java in the thread divided into two categories, namely daemon threads and user threads, when jvm start, the main thread is a method where the user thread, along with a number of user threads started there daemon threads, such as garbage collection thread. One of the biggest differences is the guardian of threads and user threads, when the end of the last non-daemon thread, the JVM will exit normally, rather than whether the current daemon thread, that thread is the guardian does not affect the exit end of the JVM, as long as there a user thread is not over, under normal circumstances, jvm will not quit. By setDeamon way to set whether the daemon thread.

Guess you like

Origin www.cnblogs.com/lijianming180/p/12099796.html