Java Multithreaded notes

Source: Internet
Author: User
Tags volatile

1. Use the new thread (runnableobj) rather than inherit from thread.
For time-consuming tasks, it should be placed in the thread execution
Call the new thread (runnable). The start () method starts the thread, and the corresponding Runnalbe.run method is called in the threads
2, the way to break the thread: Call interrupt mode, will set the interrupt state. Check this interrupt bit to determine if the thread is interrupted: Thread.CurrentThread (). isinterrupted ().
CurrentThread can be used to get the current thread.
The sleep method clears the interrupt state and throws interruptedexception.
Interrupt () interrupts the request to the line Cheng and resets the interrupt state to true.
The interrupted () method detects if the thread is interrupted, and if it clears the interrupt state.


Thread state: New,runnable can be run (the state after start is called, the state of the thread being executed, and all the waiting execution is operational), blocked is blocked, waitting,timed waiting timed wait, Terminated.


Blocked condition: 1, wait for the lock to be released, 2. When the thread waits for another thread to notify the scheduler of a condition, it enters the wait state itself, and the method has a time-out parameter, and the timeout enters the timed wait state. such as thread.sleep,object.wait (), Thread.Join (), Lock.trylock (), condition.await ()


3. Join () waits for the specified thread to be terminated, and the join (long Mills) waits for the specified thread to die or the specified number of milliseconds;
Thread.state getState () Gets the state of the thread
4. The thread inherits the priority from the parent thread. Use SetProperty to adjust the priority, take the value 0~10, the higher the value the higher the priority.
static void yield () This method causes the current execution thread to be in a concession state, with precedence being performed when there is a same priority thread present.
5, This.setdaemon (true) causes the thread to be converted to a daemon thread, which must be called before the threads are started. The purpose of a daemon thread is to serve other threads. When only the daemon thread is left, the virtual machine exits. The daemon should never access a fixed resource, such as a file or a database, because it can be interrupted at any time during an execution.
6. The thread's run cannot throw the detected exception. An undetected exception causes the thread to terminate, and the exception before the thread dies is passed to a processor that is used for an uncaught exception. The processor implements the Thread.uncaughtexcetptionhandler interface. If the default processor is not installed, the default processor is empty. Does not install the processor for a standalone thread, its processor is the Threadgroup object
Do not handle exceptions that can be passed in a catch statement.


Javap-c-V Bank is used to decompile the Bank.class


7, using synchronized to ensure the code block concurrent access.
Reentrantlock is a lock object that can be used to control concurrency. Declare a lock object in a public access code. Gets the lock before the try, and finally releases the lock. Rather than locking the object as a member of the thread.
The lock is reentrant, and the thread can repeatedly acquire the lock it has held. The lock holds a hold count, and when other methods are called in the critical section, the count is added to 1, and the calling method exits with a lock minus 1.
Pay attention to the abnormal handling of the critical section and do not jump out of the critical area due to anomalies.
8. The conditional object is used for the thread to wait for a condition to be satisfied when performing the action. A simple lock does not satisfy this scenario.
A lock can be associated with multiple condition variable condition. Banklock.newcondition () Creates a condition variable for the lock association. In the critical section, while (condition no statisfy) condition.await (), it is necessary to call in the loop body. By calling the await method in the condition variable, it will enter the waiting set of the condition, block, wait for another thread to invoke the Signalall method on the same condition (all threads waiting for this condition will be unblocked, so that the unblocked thread can be blocked after the current thread exits the block. To achieve access to objects through competition). The signal () method randomly unlocks a blocked thread, which guarantees that the unblocked thread can execute, or it will cause a deadlock.
Each conditional object manages threads that have entered a protected code segment but are not yet able to run.


There is a lock within each object, and in order to invoke the object member method declared by synchronized, an internal object lock must be obtained beforehand.
An internal object lock has only one associated condition object, and wait adds the thread to the wait set, notify/notifyall the blocking state of the waiting thread. The wait and notify methods can only be used inside synchronized to implement the conditional object's ability to wait for a condition to be implemented. Patterns are similar to await and signal.
Generally do not use synchronized and condition, priority with synchronized.


Threads have local caches and registers that can be staged in-memory values. If a lock is used to perform concurrent access to shared variables, the compiler is asked to flush the local cache (update the local value of the shared variable) as necessary to preserve the effect of the lock.
Volatile provides a lock-free mechanism for synchronous access, but does not guarantee atomicity. You can declare a shared variable to be volatile, in addition to the assignment, without completing other operations.
The atomic object can add and subtract variables in an atomic way.


9, public static final threadlocal<simpledateformat> dataformat=
New Threadlocal<simpledateformat> () {
Protect SimpleDateFormat InitialValue () {
return new SimpleDateFormat ("Yyyy-mm-dd");
}
}


10. Lock timeout: if (Mylock.trylock (100,timeunit.milliseconds)) {...} throws interruptedexception when timed out, can be used to break deadlocks.
Mycondition.await (100,timeunit.milliseconds)


11, read thread multiple write thread less with Reentrantreadwritelock.
Private RwLock = new Reentrantreadwritelock ();
Rlock=rwlock.readlock (), which is shared by all read threads, rejects the write operation with Rlock.lock () before reading, and ends with Rlock.unlock ();
Wlock=rwlock.writelock (); Repel other read operations and write operations N. Use Wlock.lock () before writing, End with Wlock.unlock ();


12, blocking queue Blockingqueue (this has several inheritance classes: Linkedblockingqueue, Linkedblockingdeque, Arrayblockingqueue) is a queue for storing shared data in a producer consumer model. This queue takes into account concurrent operations between producer consumers and handles the load balancing of producer consumers ' speed. Add an element with an offer, poll move out and return to the team header, PEEK returns the team header element (these three actions specify the time-out period for the operation).
Priorityblockingqueue priority queue.


13, Thread-safe collection: Blocking queue, Concurrenthashmap, Concurrentskiplistmap, Concurrentskiplistset (these two are thread-safe ordered set, need to comparable interface beforehand), Concurrentlinkedqueue. The size of these collections () internally needs to be traversed to determine the collection sizes, unlike the general collection.
These collections return a weakly consistent iterator that does not necessarily return the modified value, but does not return the same value two times and does not throw concurrentmodificationexception.
concurrenthashmap<e> (int initialcapacity, float loadfactor, int concurrentlevel), medium parameter is the initial capacity of the specified collection, The default is 16.concurrentLevel is the estimated number of concurrent writer threads, indicating that up to 16 write processes can be written at the same time, and many more will block the remaining threads.
Concurrenthashmap.putifabsent (K,V) is a value that inserts a KV pair when the key does not exist, otherwise the return key K corresponds to.




Write the copy of the array:
Copyonwritearraylist and Copyonwritearrayset. The write thread modifies the underlying data. This type of collection is appropriate if the number of read threads is greater than the number of write threads. Read and write can be consistent without synchronization.


It is not recommended to use any collection class that can become thread-safe through the synchronization wrapper, by adding a lock to the collection, because it is still necessary to include synchronized (Synchashmap) {...} in the code that is being accessed, it is recommended to use the Concurrentxxx collection:
list<e> syncarraylist = collections.synchronizedlist (New arraylist<e> ());
hashmap<k,v> Synchashmap = Collections.synchronizedmap (New hashmap<k,v> ());
For an array list that is often modified, using synchronized (arrayList) {} will perform better than copyonwritearraylist.




14, callback callable and future. Runnalbe is an asynchronous method with no return value, and callable and future have a return value. callable<e>{E call ();} There is only one method that returns call () with the value type E.
The future holds the asynchronous computation result, and its get (long Timeout,timeunit) can specify the time-out and the timeout interrupt. If the future is still executing, Isdone () returns false. The Cancle () method cancels the operation.


Futuretask Wrapper, can convert callable to future what runnable.
Callable<integer> mycompution=.;
futuretask<integer> task= New futuretask<integer> (mycompution);//Construct an object that is both a future and a runnable.
Thread t= new Thread (Task);
T.start ();
...
Integer result=task.get ();//The Get call is blocked until there is a result or time-out that can be obtained.


15, Actuator Executor
If there are a lot of short-life threads in your program, it is best to use a thread pool. The thread pool contains many idle threads that are ready to run. When the runnable is given to the thread pool, a thread calls Runnable.run (). When run exits, the thread goes back to the thread pool to wait for the next run.
Using a thread pool can reduce the number of concurrent threads.
There are many static methods in executor that can be used to build the thread pool: Newcachedthreadpool idle threads are saved 60s;newfixedthreadpool the number of fixed threads and idle threads persist, if the number of tasks is greater than the number of threads, Tasks that are not executed are placed in the queue waiting for idle threads to be available; Newsinglethreadpool has only one thread for sequential execution. These methods return the Threadpoolexecutor object that implements the Executorservice interface.
Future<?> Submit (runnable,t result) available in the Executorservice interface; The Future<?>submit (callable<t> Task) method submits runnable and callable objects to executorservice.
Call shutdown () to close the thread pool after the thread pool is exhausted.


Steps:
A, Executors.newfixedthreadpool ()
B, submit submitted runnable or callable object;
C, get the future object result, and call Result.get ();
D. Close thread pool shutdown ()




15. Scheduled execution (scheduled tasks)
The Scheduledexecutorservice interface has methods that are designed for tasks that are scheduled or performed repeatedly.
Scheduledexecutorservice Ss=executors.newscheduledthreadpool ();
Schedule (Callable/runnable,initdelaytime,timeunit);
Scheduleatfixedrate (Callable/runnable,initdelaytime,long period,timeunit);//Every period is executed once


16. Control Task Group
Executor can be used to control a set of related tasks.
Invokeany: Multiple tasks can be executed, as long as one execution is complete.
InvokeAll: Multiple tasks are executed and all tasks are completed before they can be ended. Use the following methods:
List<callable<t>> tasks= ...;
List<future<t>> Results=executor.invokeall (tasks);
for (future<t>res:results) {//sequential traversal takes a long time to wait for the first task, it is recommended that Executorcompletionservice be saved in the order of result generation, more efficient
Processfuturer (Result.get ());
}


17, Fork-join Framework (large task divided into small tasks, parallel execution after the merge)
The recursivetask is used to return a computed result, and recursiveaction is used for no computed results. The compute of both are used to generate and invoke subtasks and merge the results.
Class Counter extends recursivetask<integer>{//divide and conquer algorithm
Protect Integer compute () {
if (to-from<threshold) {Direct Execution (single Task)}
else{
int mid= (Low+high) >>1;
Counter first=new Counter (from,mid);//Split molecule task
Counter second=new Counter (Mid+1,high);
InvokeAll (First,second);//Scheduling All subtasks
Return First.join () +second.join ();//Merge Results
}
}
}
Main () {
Forkjoinpool pool=new Forkjoinpool ();
Pool.invoke (counter);
System.out.println (Counter.join ());
}


18. Synchronizer
Provides classes for implementing inter-thread collaboration:
Cyclicbarrier: Waits for a certain number of threads to reach a common barrier, performing a processing barrier action.


Cyclicbarrier barrier=new Cyclicbarrier (numthreads,barrieraction);//when numthreads threads reach the barrier, execute barrieraction
runnable{
public void Run () {
DoSomething ...
Barrier.await ();//wait until the barrier is open, you can set the timeout time, throw the exception timeout, cause other threads waiting for await to throw brokenbarrierexception exception.
...
}
}


Countdownlatch: Allow wait until counter is 0. Used when one or more lines Cheng wait for a specified number of events to occur. This is disposable and can only be used once.
Exchanger: Allows two threads to swap objects when they are ready to swap objects. Two threads on two different instances of the same data structure, one adds data to the instance and the other clears the data
Semaphore: Allows the thread to wait until it is allowed to execute. The number of threads used to restrict access to resources.
Semaphores manage many permits to limit the number of threads that pass through. Semaphores maintain only one count. The other thread releases the license permits by calling release ().


Synchronousqueue: Allows one thread to hand over an object to another thread. In the case of no explicit synchronization, two threads path an object from one thread to another.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Multithreaded notes

Related Article

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.