Java Common advanced Threading operations

Source: Internet
Author: User

For Java thread operation has been not very clear, today found a high-level textbook, there is a special introduction to JAVA7 support threading operations, a little record of the various types and conditions of use

1.synchronized Object Lock

Use synchronized to lock an object, but using the method in the class causes the object of the entire class to be locked, so that other threads that do not have this keyword cannot be manipulated by another thread.

Synchronized can lock any block of code and lock any lock on the object as a block of code.

2.volatile for thread synchronization

Volatile is a keyword that synchronizes variables between memory and threads, and no more than two copies of variables are stored locally.

An implementation of the 3.ReentrantLock timeout lock, which can be implemented to lock blocks of code

The code block between the. Lock () and unlock () of this class object is the block that is locked, and the method below it

Lock.trylock (ten, timeunit.seconds);

Can be used to specify the time-out.

4. Blocking queues

This is an implementation of consumer/production issues, typically using Linkedblockingqueue to specify a queue with unlimited capacity, arrayblockingqueue is a bounded blocking queue,

There is also an implementation called LinkedTransferQueue, but it is not too clear that the example in the book, it should be an on-demand queue, that is, if the queue has a thread waiting to use data, then the thread that inserts the data once started, will produce all the data needed, and once there is no waiting/ The thread that requests the data does not produce data.

5. Synchronizer

Semaphore semaphore This class is used to generate semaphores, and the so-called mechanism of semaphores is that if the semaphore is marked with the event being processed, all requests are dismissed, but if there is idle, the request is accepted.

Look at the little examples I wrote:

Importjava.util.concurrent.*;ImportJava.util.concurrent.atomic.AtomicInteger; Public classMain { Public Static voidMain (string[] args) {Executorservice Executorservice= Executors.newfixedthreadpool (10); Callable<Integer> callable =NewCallable<integer>() {@Override PublicInteger Call ()throwsException {return NewAtomicinteger (1). Incrementandget ();        }        }; Semaphore Semaphore=NewSemaphore (4,true); Try {             while(true) {                if(Semaphore.tryacquire (2, Timeunit.seconds)) { Future<Integer> future =Executorservice.submit (callable);                System.out.println (Future.get ()); }            }        }Catch(Interruptedexception e) {}Catch(Executionexception e) {}finally{executorservice.shutdown (); }    }}

What you see is that Executorservice creates 10 thread pools (called thread pools), but the semaphore is four, so you can only see four output when you execute it.

Importjava.util.concurrent.*;ImportJava.util.concurrent.atomic.AtomicInteger; Public classMain { Public Static voidMain (string[] args) {Executorservice Executorservice= Executors.newfixedthreadpool (10); Callable<Integer> callable =NewCallable<integer>() {@Override PublicInteger Call ()throwsException {return NewAtomicinteger (1). Incrementandget ();        }        }; Semaphore Semaphore=NewSemaphore (4,true); Try {             while(true) {                if(Semaphore.tryacquire (2, Timeunit.seconds)) { Future<Integer> future =Executorservice.submit (callable);                System.out.println (Future.get ());            } semaphore.release (); }        }Catch(Interruptedexception e) {}Catch(Executionexception e) {}finally{executorservice.shutdown (); }    }}

This is a method that adds a semaphore called release, which releases a semaphore license and returns it to Semaphore.

6. Barrier

As a description of the barrier: is a node, this node is a meeting point, all operations will go to this position after execution, that is to say, all the completed task of the thread to wait until other threads to complete, a bit like the concept of a daemon thread. Cyclicbarrier implements a barrier, and its construction method specifies a number and a Runnable object, which is the number of threads it dispatches to command, Runnable is the operation that is performed after all threads have ended Cyclicbarrier

This can solve some parallel algorithms, the runnable is used to merge the results (using the idea of splitting the law).

7.callable,future interface

Both of these objects are able to return the results of the county run, callable is executed by the Executorservice, the service's submit returns a future object, you can use its Get method to return the results of the callable run, But note that only after the thread has finished running will the future have a value to return

Futuretask is an object that implements both the runnable and the future interface, either with his run method or by the submit

8.Executors

A series of static methods of this class to create the thread pool and return the Executorservice object, Newfixedthreadpoll is to create a fixed-size thread pool, Newcachethreadpool is the thread pool that is automatically destroyed after 60s is created. This makes it easier to save time and memory when the number of threads changes greatly over a short period of time.

Newsinglethreadexecutor is to create a thread that can be reused.

Newscheduledthreadpool creates a thread pool of a specified size, unlike when the thread pool performs the operation of a thread, it can specify the delay and the number of times, depending on the timing. You can specify a runnable by the scheduleatfixedrate of the returned Scheduledexecutorservice object and the delay between its first execution and the next two calls

9.ForkJoinPool and Forkjointask

These two are also a way to create a thread pool, but the difference is that the threads they execute can be merged, but the task objects they execute use their abstract subclasses, which forkjointask the implementation of the abstract subclasses: Recursivetask and Recursiveaction.

The former can return a result, and the latter cannot return a result. The calculation is implemented in the Compare implementation method. After performing a task, you can call Forkjoinpool's Invoke method to submit a task, and a method called InvokeAll (), but how this method is used I'm not quite aware of it, because the all method calls the The parameter is a collection of callable objects rather than forkjointask.

10. Thread-Safe random number generation Threadlocalrandom class

In general, static methods that use it can be generated, such as:

Threadlocalrandom.current (). Nextlong (100);

Generates a random number with a lower limit of 0 and a maximum of 100.

This should be a thread-safe random-number birthdate, so you might consider using it in parallel operations.

Java Common advanced Threading operations

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.