Alibabacloud.com offers a wide variety of articles about mastering concurrency programming with java 8, easily find your mastering concurrency programming with java 8 information here online.
FinalInteger index = 5000;//the cardinality of the split task Private FinalInteger left; Private FinalInteger right; PublicFockJoin1 (integer left, integer right) { This. left =Left ; This. right =Right ; } @OverrideprotectedInteger Compute () {intsum = 0; if(Right-left //if the task is less than the cardinality, it is executed directly; like a recursive exit for(inti = left; I ) {sum+=i; } }Else{//tasks larger than cardinality, then split, similar to dichotomy, can also
creating many threads to handle, resulting in a large number of threads waiting (waiting).Co-process: Multi-tasking scheduling in single thread, and the switch between multiple tasks in a single thread.Hardware resources limit the bandwidth of upload/download speed, hard disk read and write speed and CPU processing speed. Software resources limit the number of connections to the database and socket connections.How can i solve the problem of resource limitations?
For hardware limitation
can call interrupted or isinterrupted at the appropriate time to detect the state and do the appropriate processing.>> interrupted usage scenariosInterrupt usage scenarios typically include the following:When you click the Cancel button in a desktop app;An operation exceeds a certain execution time limit when it needs to be aborted;Multiple threads do the same thing, as long as a thread succeeds when other threads can be canceled;When one or more errors in a group of threads cause an entire gro
Chapter 3rd: Sharing of objects
The understanding of the volatile keyword
a volatile variable that is used to ensure that a variable's row action is notified to other threads. When a variable is declared as a volatile type, the compiler and the runtime will notice that the variable is shared, so the operation on that variable is not reordered with other memory operations. Volatile variables are not cached to registers or other processors where they are not visible, so the most rece
It is easy to start tasks and threads. However, sometimes we want to end a task or thread prematurely, perhaps because the user canceled the operation, or the application needs to be shut down quickly.It's not easy to get tasks and threads to stop safely/quickly/reliably. Java does not provide any mechanism to safely terminate a thread, but it provides interrupts, a collaborative mechanism that enables one thread to terminate the work of another threa
NewIllegalArgumentException (...); lower = value; } Public void Setupper(intValue) {if(Value Throw NewIllegalArgumentException (...); upper = value; } }This approach restricts the state variables of the scope, so defining the lower and upper fields as volatile types does not fully implement the thread safety of the class, so synchronization is still required. Otherwise, if it happens that two threads execute Setlower and setupper at the same time using inconsistent val
elements to the queue is "C", "A", "B", and the Order of removal is "a", "B", "C", which can be seen by the nature of its "precedence".SummarizeThis article introduces three commonly used tool classes, threadlocal is used to solve the problem of multi-threaded sharing the same variable, it is equivalent to creating a thread object as a key to the target object as a value of a map, but actually and map is different, For example, a map object does not garbage-reclaims the corresponding value afte
make Mutableinteger a thread-safe class, as follows:[Java]View Plaincopy
public class synchronizedinteger
{NBSP;NBSP;
private int value;
NBSP;NBSP;
public synchronized NBSP; int get () {
return value;
}
PublicsynchronizedvoidSet (intvalue) {
this
}
}
The set and get methods are synchronized, with the same object lock, so that the Get method can see the change in the value of the set
. If a read thread attempts to acquire a write lock, it will not succeed.Lock downgradingReentrancy also allows downgrading from the write lock to a read lock, by acquiring the write lock, then the read lock and Then releasing the write lock. However, upgrading from a read lock to the write lock are not possible.ChineseLock downgradeBy acquiring a write lock, acquiring a read lock, and then releasing the write lock, Reentrant also allows the downgrade from a write lock to a read lock. However, i
completed: Number of threads in 0--thread pool: 5--Number of threads in the column: 4--Number of threads executed: 0--thread pool: 5--Number of threads in the column: 5--Number of threads executed: 0--threads in thread pool: 6--Number of threads in the column: 5 --Number of threads executed: 0thread Start, Thread:11--threads in thread pool: 7--Number of threads in the column: 5--Number of threads executed: 0thread Start, Thread:12--threads in thread pool: 8
()); System.out.println (Result.gettranslate ()); System.out.println (Result.getlistening ());}}Client:public class Exam3pool {//Current performance better way public static void main (string[] args) {//Get server CPU number int cpunum = Runtime.getruntime ( ). Availableprocessors (); System.out.println ("Number of CPUs:" + cpunum);//The appropriate number of threads is the number of CPUs executorservice pool = Executors.newfixedthreadpool (Cpunum); for (int i=0;iSummarize:By setting the public
Phaser =NewPhaser (3);//requires 3 thread synchronizationPhaser.arrive ();//notifies a participant that the current stage has been completed and should not wait for other participants to synchronizePhaser.awaitadvance (int);//If the incoming parameter is consistent with the current stage, the current thread sleeps until this stage the participant completes;Phaser.awaitadvanceinterruptibly (int);//throws an exception if interruptedPhaser.register ();//sign up for a new participantPhaser.register
(); //Add and delete operations Public synchronized voidAdd (Integer i) {set.add (i);} Public synchronized voidRemove (Integer i) {set.remove (i);} Public voidaddtenthings () {Random R=NewRandom (); for(inti = 0; I i) {Add (R.nextint ()); } //Note that this may throw an exception because the set is used here, but there is no lock, that is, the object lock that should be added to the Hiddeniterator//in the output log, our set calls the ToString method, which iterates over the contai
() { Public voidrun () {Try { //wait for all threads to startstartgate.await (); Try{task.run ();//Start Thread } finally { //notification after the thread has finished runningEndgate.countdown (); } }
1, CPU speed and memory speed is no longer an order of magnitude, not every time to the main memory read and write variables. Instead, the CPU cache: The program in the process of operation, will be the operation of the required data from the main memory copy to the CPU cache, then the CPU can be calculated directly from its cache to read data and write data to it, when the end of the operation, then the cache data into main memory.2. Volatile allows shared variables to be visible (as soon as th
that require guaranteed sequential execution of tasks * return new Finalizabledelegatedexecutorservice (new Threa Dpoolexecutor (1, 1, 0L, Timeunit.milliseconds, New Linkedblockingqueuemeaningless * / Executors.newsinglethreadexecutor (); /** * Create a fixed thread for servers that need to limit the current number of threads, load the heavier server * return new Threadpoolexecutor (Nthreads, Nthreads , 0L, Timeunit.milliseconds, New linkedblockingqueuemeaningless
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.