Java Concurrency and Multithreading Fundamentals (i)

Source: Internet
Author: User
Tags volatile

1.java Thread Status

Threads in Java can be in one of the following states:

    • NEW: Threads that have not been started so far are in this state.
    • RUNNABLE: The thread that is executing in the Java virtual machine is in this state.
    • BLOCKED: The thread that is blocked and waits for a monitor lock is in this state.
    • Waiting: The thread that waits indefinitely for another thread to perform a particular operation is in this state.
    • Timed_waiting: The thread that waits for another thread to perform an operation that depends on the specified wait time is in this state.
    • TERMINATED: The thread that has exited is in this state.

At a given point in time, a thread can only be in one state. These states are virtual machine states, and they do not reflect all operating system thread states.

1.1 New

Thread T = new MyThread (r), after which the thread is in the new state.

1.2 Runnable

After the Start method is called, the thread is in the runnable state. a runnable (running) thread may or may not be running, depending on when the operating system gives the thread the time it is running.

1.3 Blocked

A thread attempts to acquire an internal object lock (not a lock in the java.util.concurrent), and when the lock is held by another thread, the object enters a blocking state (Blocked).

1.4 Waiting

A thread is waiting because it calls one of the following methods:

    • Object.wait with no time-out value
    • Thread.Join with no time-out value
    • Lock or condition in the java.util.concurrent
1.5 timed_waiting

A thread is in a timed wait state because it calls one of the following methods with the specified positive wait time:

    • Thread.Sleep
    • Object.wait with time-out value
    • Thread.Join with time-out value
    • Lock.trylock in Java.util.concurrent and Condition.await's chronograph version
1.6 Terminated

Two reasons the thread was terminated:

    • The Run method exits gracefully and terminates naturally.
    • Unexpected termination due to an uncaught exception terminating the Run method

2. Synchronization (some of the lower-level solutions)

Synchronization has two meanings: mutex and memory visibility

    • 2.1 Lock Object Lock and conditional object condition
    • 2.2synchronized keywords
    • 2.3volatile Domain
    • 2.4 Atomic Class
    • 2.5ThreadLocal
2.1 Lock Object Lock and conditional object condition

Java introduces the Synchronized keyword in order to facilitate programmers writing concurrency code. To understand the meaning of the Synchronized keyword, you must first know the two concepts: Lock object and Condition object.

2.1.1 Lock Object

The lock object is introduced to ensure that only one thread can access the critical section at any time. The basic structure for using lock to protect your code is as follows:

Mylck.lock (); Try {    critical section}finally{    mylock.unlock ();}

This result ensures that only one thread enters the critical section at any time. Once a thread holds the lock object, no other thread can pass the lock statement. When other threads call lock, they are blocked until the first thread releases the lock object.

Example of using a lock to protect the transfer method of the Bank class:

 Public classBank {PrivateLock Banklock =NewReentrantlock (); //...         Public voidTransferintFromintTo,intamount)        {Banklock.lock (); Try{System.out.println (Thread.CurrentThread ()); Accounts[from]-=amount; Accounts[to]+=amount; System.out.printf ("Total Balance:%10.2f%n", Gettotalbalance ()); }        finally{banklock.unlock (); }    }}

Can I re-enter the lock?

The locks in the bank example above are reentrant. The re-entry lock can be referenced here.

2.1.2 Condition Object

Why do I need conditional objects?

The bank example illustrates the process of transferring money from one bank account to another. However, the above-mentioned internal transfer process still needs to be perfected: if the balance of the transfer account is not enough, you should wait for the other account to transfer to yourself before performing the above transfers.

 public  void  transfer (int  from, int  to,int   amount) {Banklock.lock ();  try  { while  (Accounts[from] < amount) { //  wait   ...}  //  transfer funds              ...        }         finally  {Banklock.unlock (); }    }

If the balance of the transferred account is not sufficient, you should wait for the other account to transfer to yourself before performing the above transfers. However, the current thread has just acquired exclusive access to Banklock, so it is not possible for other threads to have the opportunity to execute the transfer method. What do we do? The solution is to have the current thread release the Banklock lock object and wait for the account balance to meet the criteria to continue. Conditional objects can help us solve this problem, which is why we need conditional objects.

A lock can have one or more related conditional objects. You can use the Newcondition () instance method of the lock object to get a conditional object.

Calling the await () method of the condition object makes it appropriate for the front-thread to enter the waiting set for the condition.

Calling the Signalall () method of the condition object causes all processes waiting on the condition object to be awakened.

Importjava.util.concurrent.locks.Condition;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock; Public classBank {PrivateLock Banklock =NewReentrantlock (); PrivateCondition sufficientfunds =banklock.newcondition (); Private Final Double[] accounts;  PublicBank (intNDoubleinitialbalance) {Accounts=New Double[n];  for(inti = 0; i < accounts.length; i++) {Accounts[i]=initialbalance; }    }         Public voidTransferintFromintTo,intAmountthrowsinterruptedexception{Banklock.lock (); Try{             while(Accounts[from] <amount) sufficientfunds.await ();            System.out.println (Thread.CurrentThread ()); Accounts[from]-=amount; System.out.printf ("%10.2f from%d to%d", amount,from,to); Accounts[to]+=amount; System.out.printf ("Total Balance:%10.2f%n", Gettotalbalance ());                    Sufficientfunds.signalall (); }        finally{banklock.unlock (); }    }     Public Doublegettotalbalance () {banklock.lock (); Try{            Doublesum = 0;  for(Doubled:accounts) {Sum+=D; }            returnsum; }        finally{banklock.unlock (); }    }}

Note: The call to await should be in the following loop body:

 while (! (ok to proceed))    Condition.await ();

Summarize:

    • Locks are used to protect code fragments, and only one thread executes the protected code at any time.
    • Locks can manage threads that attempt to enter a protected code segment.
    • The lock one has one or more related conditional objects.
    • Each conditional object manages threads that have entered a protected code segment but are not yet able to run.
2.2 Synchronized Keywords

Starting with version 1.0, each object in Java has an internal lock. If a method is declared with the Synchronized keyword, then the lock of the object to which the method belongs will protect the entire method. In other words, to invoke the method, the thread must obtain an internal object lock.

Other words

 Public synchronized void method () {    method body}

Equivalent to

 Public void method () {    this. Intrinsiclock.lock ();     Try {        method body    }    finally{        this. Intrinsiclock.unlock ();    }}

An internal object lock has only one related condition object. The wait method in the object class adds a thread to the wait set, and the Notify/notifyall method unlocks the blocking state of the waiting thread. Calling wait or Notifyall is equivalent to

Intrinsiclock.await (); Intrinsiclock.signalall ();

Understanding the internal equivalence forms of Wait,notify/notifyall and other methods is easy to understand why calls to Wait,notify/notifyall and other methods can only be used in synchronous control methods or in synchronous control blocks.

Interview question: What is the difference between sleep and wait in Java?

    • Source: Sleep comes from the thread class, and wait comes from the object class.
    • Lock: The most important thing is that 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.
    • Use range: Wait,notify and notifyall can only be used in synchronous control methods or synchronization control blocks, and sleep can be used anywhere.

The bank classes in version synchronized are as follows:

 Public classBank {Private Final Double[] accounts;  Public synchronized voidTransferintFromintTo,intAmountthrowsinterruptedexception{ while(Accounts[from] <amount) wait ();        System.out.println (Thread.CurrentThread ()); Accounts[from]-=amount; System.out.printf ("%10.2f from%d to%d", amount,from,to); Accounts[to]+=amount; System.out.printf ("Total Balance:%10.2f%n", Gettotalbalance ());    Notifyall (); }             Public synchronized Doublegettotalbalance () {...}}
2.3volatile Domain

Synchronization consists of two aspects: mutex and memory visibility. Volatile-Modified field guarantees memory visibility, but does not guarantee mutual exclusion (atomicity).

the locking mechanism ensures both visibility and atomicity, while volatile variables only ensure visibility .

2.4 Atomic Class

There are many classes in the Java.util.concurrent.atomic package that use very efficient machine-level instructions (rather than locks) to ensure the atomicity of their operations.

Application programmers should not use these classes, they are intended for use only by system programmers who develop concurrency tools.

2.5 Threadlocal Class

Sometimes you might want to avoid sharing variables and use the Threadlocal class to provide each thread with its own instance.

The field of the Threadlocal class is usually a static variable, otherwise it is completely unnecessary if it is an instance variable.

 PackageThink.in.java.chap21.section3;ImportJava.util.Random;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.TimeUnit;/*** Private threadlocal<integer> value = new threadlocal<integer> (); * This illustration: * If you remove the static, each THREADLOCALV The Ariableholder object has a value field, and each thread that accesses the object has a local value variable. * */ Public classThreadlocalvariableholderextendsthread{PrivateThreadlocal<integer> value =NewThreadlocal<integer>(){        PrivateRandom random =NewRandom (47); protected synchronizedInteger InitialValue () {returnRandom.nextint (10000);    }    };  Public voidincrement () {Value.set (Value.get ()+1); }     Public intget () {returnValue.get (); }     Public voidrun () {increment (); System.out.println (Thread.CurrentThread ()+" | "+ This); }     PublicString toString () {return"[" +get () + ", value=" + value + "]"; }     Public Static voidMain (string[] args)throwsException {executorservice exec= Executors.newfixedthreadpool (8);  for(inti = 0; I < 2; i++) {Threadlocalvariableholder T=NewThreadlocalvariableholder ();  for(intj = 0; J < 4; J + +) {Exec.execute (t); }} TimeUnit.SECONDS.sleep (3);    Exec.shutdownnow (); }}

3. Blocking queue Blockingqueue (synchronous high-level solution)

The underlying component blocks of Java concurrent programming are described earlier, and should be kept as far away from the underlying structure as possible in actual programming. Many of the problems in multi-threading are producer-consumer models that can be formalized gracefully through one or more queues. Starting with 5.0, the JDK provides the official implementation of the blocking queue in the Java.util.concurrent package.

The difference between a blocking queue and a normal queue is that when the queue is empty, the operation to get elements from the queue is blocked, or when the queue is full, the operation to add elements to the queue is blocked. Threads that attempt to fetch elements from an empty blocking queue are blocked until other threads insert new elements into the empty queue. Similarly, threads that attempt to add new elements to the full blocking queue are also blocked until other threads make the queue idle again, such as removing one or more elements from the queue, or completely emptying the queue.

The blockingqueue method appears in four forms, for operations that cannot be met immediately but may be satisfied at some point in the future, and these four forms are handled differently: the first is to throw an exception, and the second is to return a special value (null or false, depending on the operation), the third is to block the current thread indefinitely until the operation succeeds, and the fourth is to block only within the given maximum time limit before discarding. These methods are summarized in the following table:

put (e) td>
  Throw exception Special value block timeout /td>
Insert Add (E) offer (e) offer (e, time, unit)
Remove Remove () poll () Take () Poll (time, unit)
Check Element () Peek () unavailable Not available

Blockingqueue does not accept null elements. Some implementations throw NullPointerExceptionwhen attempting to add,put , or offer a null element. null is used as a warning value indicating that the poll operation failed.

There are known implementation classes:
Arrayblockingqueue, Delayqueue, Linkedblockingdeque, Linkedblockingqueue, Priorityblockingqueue, SynchronousQueue

Java Concurrency and Multithreading Fundamentals (i)

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.