Advanced Java Multithreading Java 8 Multi- Threading with Lambda Exchange Ideas Page 4 Advanced Multi-Threading java util concurrent - Executor
Previous PDF | Next PDF |
[PDF] Lecture 8 Java SE – Advanced Multithreading - acsasero
Advanced Java Multithreading Java 8 Multi- Threading with Lambda Exchange Ideas Page 4 Advanced Multi-Threading java util concurrent - Executor
[PDF] Multithreading
The Java programming language itself uses a thread to do garbage collection tem-level programming, we suggest that you turn to a more advanced reference, such SwingWorker class, described in http://java sun com/docs/books/tutorial/
[PDF] Multithreading
Java Virtual Machine (JVM) creates threads to run programs and threads to perform These interfaces should be used only by advanced program- mers who are The concepts are important to understand, even if an application does not use
[PDF] Java Thread Programming - Free
Start by learning the basics of multithreaded programming in Java and work up to the more advanced concepts • Suitable tutorial for Java developers that have
[PDF] Java - Multithreading - Tutorialspoint
Multi threading enables you to write in a way where multiple activities can Every Java thread has a priority that helps the operating system determine the order in which programming in Java, you would need to have the following concepts
[PDF] Introduction to Java threads - Free Java Guide & Tutorials
language, but who have limited experience with multithreading or concurrency At the completion of this tutorial, you should be able to write simple programs that
[PDF] Java Concurrency Essentials
concurrent code and you will learn about concepts like atomicity, synchronization and thread safety As you advance, the following lessons will deal with the
[PDF] Advanced Java Programming
In this tutorial we are going to cover advanced Java concepts, assuming that our Java runtime guarantees that it will be executed only once and in thread-safe
[PDF] Java Concurrency Framework
O To write thread safe programs that allow multiple threads to work on shared resources without O This presentation will introduce the various concepts that
[PDF] Multithreaded Programming with JAVA Technology
Programming with Java Technology is the first complete guide to multithreaded The basic concept of multithreaded programming has existed in research and In the nineteenth century, when trains were still advanced technology and
[PDF] advanced numerology pdf
[PDF] advanced oops concepts in java pdf
[PDF] advanced oracle pl/sql developer's guide pdf
[PDF] advanced oracle sql programming the expert guide to writing complex queries pdf
[PDF] advanced oracle sql queries examples with answers
[PDF] advanced oracle sql queries for practice
[PDF] advanced oracle sql queries interview questions
[PDF] advanced oracle sql tuning burleson pdf
[PDF] advanced oracle sql tuning pdf download
[PDF] advanced oracle sql tuning pdf free download
[PDF] advanced oracle sql tuning the definitive reference pdf
[PDF] advanced oracle sql tuning the definitive reference pdf free download
[PDF] advanced oracle sql tutorial
[PDF] advanced php book pdf
CristianToma-BusinessCard
1.ThreadsIssuesAdvantagesofMultithreading:Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671§Reactivesystems-constantlymonitoring§Moreresponsivetouserinput-GUIapplicationcaninterruptatime-consumingtask§Servercanhandlemultipleclientssimultaneously§CantakeadvantageofparallelprocessingWhenMultithreading?:Concurrency(incl.Cooperation)and/orParallelism
1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671Thejoin()MethodYoucanusethejoin()methodtoforceonethreadtowaitforanotherthreadtofinish.The numbers after 50 are printed after thread printAis finished.
printA.join() -char token +getToken +setToken +paintCompone t +mouseClickedThread
print100 -char token +getToken +setToken +paintCompo net +mouseClicke dWait for printA
to finish +getToken +setToken +paintComponet +mouseClickedThread
printA -char token +getToken +setToken +paintCompo net +mouseClicke d printA finished -char token public void run() { //print100 - methodThread thread4printA = new Thread(
new PrintChar('A', 40)); thread4printA.start(); try { for (int i = 1; i <= lastNum; i++) {System.out.print(" " + i);
if (i == 50) thread4printA.join(); catch (InterruptedException ex) {1.ThreadsStates-RecapitulationCISCO Copyright
1.ThreadsStates-UpdateLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
New Ready
Thread created
Finished
Running
start() run()Wait for
target to finish join() run() returns yield(), or time out interrupt()Wait for time
outWait to be
notified sleep() wait() Target finished notify() or notifyAll()Time out
Blocked
Interrupted()
A thread can be in one of five states: New, Ready, Running, Blocked, or Finished.1.ThreadsMethodsLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671isAlive()•methodusedtofindoutthestateofathread.•returnstrue:threadisintheReady,Blocked,orRunningstate•returnsfalse:threadisnewandhasnotstartedorifitisfinished.interrupt()fathreadiscurrentlyintheReadyorRunningstate,itsinterruptedflagisset;ifathreadiscurrentlyblocked,itisawakenedandenterstheReadystate,andanjava.io.InterruptedExceptionisthrown.TheisInterrupt()methodtestswhetherthethreadisinterrupted.
1.ThreadsMethodsLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671Thedeprecatedstop(),suspend(),andresume()MethodsNOTE:TheThreadclassalsocontainsthestop(),suspend(),andresume()methods.AsofJava2,thesemethodsaredeprecated(oroutdated)becausetheyareknowntobeinherentlyunsafe.YoushouldassignnulltoaThreadvariabletoindicatethatitisstoppedratherthanusethestop()method.
1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671•EachthreadisassignedadefaultpriorityofThread.NORM_PRIORITY(constantof5).YoucanresetthepriorityusingsetPriority(intpriority).•SomeconstantsforprioritiesincludeThread.MIN_PRIORITYThread.MAX_PRIORITYThread.NORM_PRIORITY•Bydefault,athreadhastheprioritylevelofthethreadthatcreatedit.ThreadPriority•Anoperatingsystem'sthreadschedulerdetermineswhichthreadrunsnext.•Mostoperatingsystemsusetimeslicingforthreadsofequalpriority.•Preemptivescheduling:whenathreadofhigherpriorityenterstherunningstate,itpreemptsthecurrentthread.•Starvation:Higher-prioritythreadscanpostpone(possibleforever)theexecutionoflower-prioritythreads.
1.ThreadsConcurrency&ParallelismLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671ThreadPool•Startinganewthreadforeachtaskcouldlimitthroughputandcausepoorperformance.•Athreadpoolisidealtomanagethenumberoftasksexecutingconcurrently.•ExecutorinterfaceforexecutingRunnableobjectsinathreadpool•ExecutorServiceisasub-interfaceofExecutor.
Shuts down the executor, but allows the tasks in the executor to complete. Once shutdown, it cannot accept new tasks. Shuts down the executor immediately even though there are unfinished threads in the pool. Returns a list of unfinished tasks.Returns true if the executor has been shutdown.
Returns true if all tasks in the pool are terminated. "interface» java.util.concurrent.Executor +execute(Runnable object): voidExecutes the runnable task.
"interface» java.util.concurrent.ExecutorService +shutdown(): void +shutdownNow(): List1.ThreadsConcurrency&ParallelismLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671ThreadPoolTocreateanExecutorobject,usethestaticmethodsintheExecutorsclass.
1.ThreadsConcurrency&ParallelismLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
1.ThreadsConcurrency&ParallelismLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671importjava.util.concurrent.*; classPrintCharimplementsRunnable { privatecharcharacter;privateintnoOfTimes;PrintChar(charch, intn) {character= ch;noOfTimes= n;}publicvoidrun() {for(inti=0; i 1.ThreadsConcurrency&Parallelism
1.ThreadsConcurrency&Parallelismhttp://www.vogella.com/tutorials/JavaConcurrency/article.html"Classic"ThreadPool,ExecutorFramework,Callable&FuturepublicclassMyRunnableimplementsRunnable {privatefinallongcountUntil;MyRunnable(longcountUntil) {this.countUntil= countUntil;}@Overridepublicvoidrun() {longsum = 0;for(longi= 1; i< countUntil; i++) {sum += i;}System.out.println(sum);}}
1.ThreadsConcurrency&Parallelismhttp://www.vogella.com/tutorials/JavaConcurrency/article.html"Classic"ThreadPool,ExecutorFramework,Callable&Futureimport java.util.ArrayList;import java.util.List;publicclassProgMain{publicstaticvoidmain(String[] args) {// We will store the threads so that we can check if they are doneList threads = newArrayList();for(inti = 0; i < 500; i++) {Runnable task = newMyRunnable(10000000L + i);Thread worker = newThread(task);worker.setName(String.valueOf(i));// Start the thread, never call method run() directworker.start(); threads.add(worker);}intrunning = 0; do{running = 0; for(Thread thread: threads) {if(thread.isAlive()) { running++; }}System.out.println("We have "+ running + " running threads. ");} while(running > 0); } //end main} //end class
1.ThreadsConcurrency&Parallelismhttp://www.vogella.com/tutorials/JavaConcurrency/article.html"Classic"ThreadPool,ExecutorFramework,Callable&Futureimportjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;publicclassMain {privatestaticfinalintNTHREDS= 10;publicstaticvoidmain(String[] args) {ExecutorServiceexecutor = Executors.newFixedThreadPool(NTHREDS);for(inti = 0; i < 500; i++) {Runnable worker = newMyRunnable(10000000L + i);executor.execute(worker);}// This will make the executor accept no new threads// and finish all existing threads in the queueexecutor.shutdown();// Wait until all threads are finishexecutor.awaitTermination();System.out.println("Finished all threads");}}
1.ThreadsConcurrency&Parallelismhttp://www.vogella.com/tutorials/JavaConcurrency/article.html"Classic"ThreadPool,ExecutorFramework,Callable&Future//package de.vogella.concurrency.callables;importjava.util.concurrent.Callable;publicclassMyCallableimplementsCallable { @OverridepublicLong call() throwsException { longsum = 0;for(longi = 0; i <= 100; i++) { sum += i;} returnsum; }}
1.ThreadsConcurrency&Parallelismhttp://www.vogella.com/tutorials/JavaConcurrency/article.htmlimportjava.util.*;importjava.util.concurrent.*;publicclassCallableFutures{privatestaticfinalintNTHREDS= 10;publicstaticvoidmain(String[] args) {ExecutorServiceexecutor = Executors.newFixedThreadPool(NTHREDS);List> list = newArrayList>();for(inti = 0; i < 20000; i++) {Callable worker = newMyCallable();Future submit = executor.submit(worker);list.add(submit);}longsum = 0;// now retrieve the result -System.out.println(list.size());for(Future future : list) { try{sum += future.get();} catch(InterruptedExceptione) {e.printStackTrace();} catch(ExecutionExceptione) {e.printStackTrace();}}System.out.println(sum);executor.shutdown();}}"Classic"ThreadPool,ExecutorFramework,Callable&Future
1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671Asharedresourcemaybecorruptedifitisaccessedsimultaneouslybymultiplethreads.Example:twounsynchronizedthreadsaccessingthesamebankaccountmaycauseconflict.Stepbalance thread[i] thread[j]
10 newBalance = bank.getBalance() + 1;
20 newBalance = bank.getBalance() + 1;
31 bank.setBalance(newBalance);
41 bank.setBalance(newBalance);
1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671Example:ShowingResourceConflict-AccountWithoutSynch.java•Objective:Writeaprogramthatdemonstratestheproblemofresourceconflict.Supposethatyoucreateandlaunchonehundredthreads,eachofwhichaddsapennytoanaccount.Assumethattheaccountisinitiallyempty.
Account
-balance: int +getBalance(): int +deposit(amount: int): void 100
AccountWithoutSync
-bank: Account -thread: Thread[] +main(args: String[]): void AddAPennyTask
+run(): void java.lang.Runnable -char token +getToken +setToken +paintComponet +mouseClicked 1 1 1 1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671RaceConditionWhat,then,causedtheerrorintheexample?Hereisapossiblescenario:•Effect: Task 1 did nothing (in Step 4 Task 2 overrides the result)•Problem: Task 1and Task 2are accessing a common resource in a way that causes conflict. •Known as a race conditionin multithreaded programs. •A thread-safeclass does not cause a race condition in the presence of multiple threads. •The Accountclass is not thread-safe.
Step balance Task 1 Task 2
1 0 newBalance = balance + 1;
2 0 newBalance = balance + 1;
3 1 balance = newBalance;
4 1 balance = newBalance;
synchronized•Problem:raceconditions•Solution:giveexclusiveaccesstoonethreadatatimetocodethatmanipulatesasharedobject.•Synchronizationkeepsotherthreadswaitinguntiltheobjectisavailable.•Thesynchronizedkeywordsynchronizesthemethodsothatonlyonethreadcanaccessthemethodatatime.•ThecriticalregionintheAccountWithoutSynch.javaistheentiredepositmethod.•Onewaytocorrecttheprobleminsourcecode:makeAccountthread-safebyaddingthesynchronizedkeywordindeposit:publicsynchronizedvoiddeposit(doubleamount)1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
SynchronizingInstanceMethodsandStaticMethods•Asynchronizedmethodacquiresalockbeforeitexecutes.•Instancemethod:thelockisontheobjectforwhichitwasinvoked.•Staticmethod:thelockisontheclass.•Ifonethreadinvokesasynchronizedinstancemethod(respectively,staticmethod)onanobject,thelockofthatobject(respectively,class)isacquired,thenthemethodisexecuted,andfinallythelockisreleased.•Anotherthreadinvokingthesamemethodofthatobject(respectively,class)isblockeduntilthelockisreleased.1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Acquire a lock on the object account
-char token +getToken +setToken +paintComponet +mouseClicked Execute the deposit method
-char token +getToken +setToken +paintComponet +mouseClicked Release the lock
-char token +getToken +setToken +paintComponet +mouseClicked Task 1
-char token +getToken +setToken +paintComponet +mouseClicked Acqurie a lock on the object account
-char token +getToken +setToken +paintComponet +mouseClicked Execute the deposit method
-char token +getToken +setToken +paintComponet Release the lock
Task 2
-char token +getToken +setToken +paintComponet +mouseClicked Wait to acquire the lock
-char token +getToken +setToken +paintComponet +mouseClicked 1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
SynchronizingStatements•Invokingasynchronizedinstancemethodofanobjectacquiresalockontheobject.•Invokingasynchronizedstaticmethodofaclassacquiresalockontheclass.•Asynchronizedblockcanbeusedtoacquirealockonanyobject,notjustthisobject,whenexecutingablockofcode.synchronized(expr){statements;}•exprmustevaluatetoanobjectreference.•Iftheobjectisalreadylockedbyanotherthread,thethreadisblockeduntilthelockisreleased.•Whenalockisobtainedontheobject,thestatementsinthesynchronizedblockareexecuted,andthenthelockisreleased.1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
SynchronizingStatementsvs.MethodsAnysynchronizedinstancemethodcanbeconvertedintoasynchronizedstatement.Supposethatthefollowingisasynchronizedinstancemethod:publicsynchronizedvoidxMethod(){//methodbody}ThismethodisequivalenttopublicvoidxMethod(){synchronized(this){//methodbody}}1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Same as ReentrantLock(false).
Creates a lock with the given fairness policy. When the fairness is true, the longest-waiting thread will get the lock. Otherwise, there is no particular access order. "interface» java.util.concurrent.locks.Lock +lock(): void +unlock(): void +newCondition(): Condition Acquires the lock.
Releases the lock.
Returns a new Condition instance that is bound to this Lock instance.
java.util.concurrent.locks.ReentrantLock +ReentrantLock() +ReentrantLock(fair: boolean) 1.ThreadsConcurrency-SynchronizationusingLocksLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
FairnessPolicy•ReentrantLock:concreteimplementationofLockforcreatingmutuallyexclusivelocks.•Createalockwiththespecifiedfairnesspolicy.•Truefairnesspoliciesguaranteethelongest-waitthreadtoobtainthelockfirst.•Falsefairnesspoliciesgrantalocktoawaitingthreadwithoutanyaccessorder.•Programsusingfairlocksaccessedbymanythreadsmayhavepooroverallperformancethanthoseusingthedefaultsetting,buthavesmallervariancesintimestoobtainlocksandguaranteelackofstarvation.1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Example:UsingLocksThisexamplerevisesAccountWithoutSync.javainAccountWithoutSyncUsingLock.javatosynchronizetheaccountmodificationusingexplicitlocks.1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
"interface» java.util.concurrent.Condition +await(): void +signal(): void +signalAll(): Condition Causes the current thread to wait until the condition is signaled. Wakes up one waiting thread.
Wakes up all waiting threads.
1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
while (balance < withdrawAmount) newDeposit.await(); Withdraw Task
-char token +getToken +setToken +paintComponet +mouseClicked balance -= withdrawAmount -char token +getToken +setToken lock.unlock(); Deposit Task
-char token +getToken +setToken +paintComponet +mouseClicked lock.lock(); -char token +getToken +setToken +paintComponet +mouseClicked newDeposit.signalAll(); balance += depositAmount -char token +getToken +setToken +paintComponet +mouseClicked lock.unlock(); -char token lock.lock(); -char token +getToken +setToken +paintComponet +mouseClicked Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Example:ThreadCooperationWriteaprogramthatdemonstratesthreadcooperation(ThreadCooperation.java).Supposethatyoucreateandlaunchtwothreads,onedepositstoanaccount,andtheotherwithdrawsfromthesameaccount.Thesecondthreadhastowaitiftheamounttobewithdrawnismorethanthecurrentbalanceintheaccount.Whenevernewfundisdepositedtotheaccount,thefirstthreadnotifiesthesecondthreadtoresume.Iftheamountisstillnotenoughforawithdrawal,thesecondthreadhastocontinuetowaitformorefundintheaccount.Assumetheinitialbalanceis0andtheamounttodepositandtowithdrawisrandomlygenerated.Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 01360126711.ThreadsCooperation
Java'sBuilt-inMonitors•LocksandconditionsarenewstartingwithJava5.•PriortoJava5,threadcommunicationswereprogrammedusingobject'sbuilt-inmonitors.•Locksandconditionsaremorepowerfulandflexiblethanthebuilt-inmonitor.•Amonitorisanobjectwithmutualexclusionandsynchronizationcapabilities.•Onlyonethreadcanexecuteamethodatatimeinthemonitor.•Athreadentersthemonitorbyacquiringalock(synchronizedkeywordonmethod/block)onthemonitorandexitsbyreleasingthelock.•Athreadcanwaitinamonitoriftheconditionisnotrightforittocontinueexecutinginthemonitor.•Anyobjectcanbeamonitor.Anobjectbecomesamonitoronceathreadlocksit.Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 01360126711.ThreadsSynchronization-Monitors
wait(),notify(),andnotifyAll()Usethewait(),notify(),andnotifyAll()methodstofacilitatecommunicationamongthreads.Thewait(),notify(),andnotifyAll()methodsmustbecalledinasynchronizedmethodorasynchronizedblockonthecallingobjectofthesemethods.Otherwise,anIllegalMonitorStateExceptionwouldoccur.Thewait()methodletsthethreadwaituntilsomeconditionoccurs.Whenitoccurs,youcanusethenotify()ornotifyAll()methodstonotifythewaitingthreadstoresumenormalexecution.ThenotifyAll()methodwakesupallwaitingthreads,whilenotify()picksuponlyonethreadfromawaitingqueue.Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 01360126711.ThreadsSynchronization-Monitors
synchronized (anObject) { try { // Wait for the condition to become true while (!condition) anObject.wait(); // Do something when condition is true catch (InterruptedException ex) { ex.printStackTrace(); Task 1
synchronized (anObject) { // When condition becomes true anObject.notify(); or anObject.notifyAll(); Task 2
resume 1.ThreadsSynchronization-MonitorsLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
while (count == CAPACITY) notFull.await(); -char token +getToken +setToken +paintComponet +mouseClicked Task for adding an int
-char token +getToken +setToken +paintComponet +mouseClicked Add an int to the buffer
-char tokenquotesdbs_dbs11.pdfusesText_17
1.ThreadsConcurrency&Parallelism
1.ThreadsConcurrency&Parallelismhttp://www.vogella.com/tutorials/JavaConcurrency/article.html"Classic"ThreadPool,ExecutorFramework,Callable&FuturepublicclassMyRunnableimplementsRunnable {privatefinallongcountUntil;MyRunnable(longcountUntil) {this.countUntil= countUntil;}@Overridepublicvoidrun() {longsum = 0;for(longi= 1; i< countUntil; i++) {sum += i;}System.out.println(sum);}}
1.ThreadsConcurrency&Parallelismhttp://www.vogella.com/tutorials/JavaConcurrency/article.html"Classic"ThreadPool,ExecutorFramework,Callable&Futureimport java.util.ArrayList;import java.util.List;publicclassProgMain{publicstaticvoidmain(String[] args) {// We will store the threads so that we can check if they are doneList threads = newArrayList();for(inti = 0; i < 500; i++) {Runnable task = newMyRunnable(10000000L + i);Thread worker = newThread(task);worker.setName(String.valueOf(i));// Start the thread, never call method run() directworker.start(); threads.add(worker);}intrunning = 0; do{running = 0; for(Thread thread: threads) {if(thread.isAlive()) { running++; }}System.out.println("We have "+ running + " running threads. ");} while(running > 0); } //end main} //end class
1.ThreadsConcurrency&Parallelismhttp://www.vogella.com/tutorials/JavaConcurrency/article.html"Classic"ThreadPool,ExecutorFramework,Callable&Futureimportjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;publicclassMain {privatestaticfinalintNTHREDS= 10;publicstaticvoidmain(String[] args) {ExecutorServiceexecutor = Executors.newFixedThreadPool(NTHREDS);for(inti = 0; i < 500; i++) {Runnable worker = newMyRunnable(10000000L + i);executor.execute(worker);}// This will make the executor accept no new threads// and finish all existing threads in the queueexecutor.shutdown();// Wait until all threads are finishexecutor.awaitTermination();System.out.println("Finished all threads");}}
1.ThreadsConcurrency&Parallelismhttp://www.vogella.com/tutorials/JavaConcurrency/article.html"Classic"ThreadPool,ExecutorFramework,Callable&Future//package de.vogella.concurrency.callables;importjava.util.concurrent.Callable;publicclassMyCallableimplementsCallable { @OverridepublicLong call() throwsException { longsum = 0;for(longi = 0; i <= 100; i++) { sum += i;} returnsum; }}
1.ThreadsConcurrency&Parallelismhttp://www.vogella.com/tutorials/JavaConcurrency/article.htmlimportjava.util.*;importjava.util.concurrent.*;publicclassCallableFutures{privatestaticfinalintNTHREDS= 10;publicstaticvoidmain(String[] args) {ExecutorServiceexecutor = Executors.newFixedThreadPool(NTHREDS);List> list = newArrayList>();for(inti = 0; i < 20000; i++) {Callable worker = newMyCallable();Future submit = executor.submit(worker);list.add(submit);}longsum = 0;// now retrieve the result -System.out.println(list.size());for(Future future : list) { try{sum += future.get();} catch(InterruptedExceptione) {e.printStackTrace();} catch(ExecutionExceptione) {e.printStackTrace();}}System.out.println(sum);executor.shutdown();}}"Classic"ThreadPool,ExecutorFramework,Callable&Future
1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671Asharedresourcemaybecorruptedifitisaccessedsimultaneouslybymultiplethreads.Example:twounsynchronizedthreadsaccessingthesamebankaccountmaycauseconflict.Stepbalance thread[i] thread[j]
10 newBalance = bank.getBalance() + 1;
20 newBalance = bank.getBalance() + 1;
31 bank.setBalance(newBalance);
41 bank.setBalance(newBalance);
1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671Example:ShowingResourceConflict-AccountWithoutSynch.java•Objective:Writeaprogramthatdemonstratestheproblemofresourceconflict.Supposethatyoucreateandlaunchonehundredthreads,eachofwhichaddsapennytoanaccount.Assumethattheaccountisinitiallyempty.
Account
-balance: int +getBalance(): int +deposit(amount: int): void 100AccountWithoutSync
-bank: Account -thread: Thread[] +main(args: String[]): voidAddAPennyTask
+run(): void java.lang.Runnable -char token +getToken +setToken +paintComponet +mouseClicked 1 1 11.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671RaceConditionWhat,then,causedtheerrorintheexample?Hereisapossiblescenario:•Effect: Task 1 did nothing (in Step 4 Task 2 overrides the result)•Problem: Task 1and Task 2are accessing a common resource in a way that causes conflict. •Known as a race conditionin multithreaded programs. •A thread-safeclass does not cause a race condition in the presence of multiple threads. •The Accountclass is not thread-safe.
Step balance Task 1 Task 2
1 0 newBalance = balance + 1;
2 0 newBalance = balance + 1;
3 1 balance = newBalance;
4 1 balance = newBalance;
synchronized•Problem:raceconditions•Solution:giveexclusiveaccesstoonethreadatatimetocodethatmanipulatesasharedobject.•Synchronizationkeepsotherthreadswaitinguntiltheobjectisavailable.•Thesynchronizedkeywordsynchronizesthemethodsothatonlyonethreadcanaccessthemethodatatime.•ThecriticalregionintheAccountWithoutSynch.javaistheentiredepositmethod.•Onewaytocorrecttheprobleminsourcecode:makeAccountthread-safebyaddingthesynchronizedkeywordindeposit:publicsynchronizedvoiddeposit(doubleamount)1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
SynchronizingInstanceMethodsandStaticMethods•Asynchronizedmethodacquiresalockbeforeitexecutes.•Instancemethod:thelockisontheobjectforwhichitwasinvoked.•Staticmethod:thelockisontheclass.•Ifonethreadinvokesasynchronizedinstancemethod(respectively,staticmethod)onanobject,thelockofthatobject(respectively,class)isacquired,thenthemethodisexecuted,andfinallythelockisreleased.•Anotherthreadinvokingthesamemethodofthatobject(respectively,class)isblockeduntilthelockisreleased.1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Acquire a lock on the object account
-char token +getToken +setToken +paintComponet +mouseClickedExecute the deposit method
-char token +getToken +setToken +paintComponet +mouseClickedRelease the lock
-char token +getToken +setToken +paintComponet +mouseClickedTask 1
-char token +getToken +setToken +paintComponet +mouseClickedAcqurie a lock on the object account
-char token +getToken +setToken +paintComponet +mouseClickedExecute the deposit method
-char token +getToken +setToken +paintComponetRelease the lock
Task 2
-char token +getToken +setToken +paintComponet +mouseClickedWait to acquire the lock
-char token +getToken +setToken +paintComponet +mouseClicked1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
SynchronizingStatements•Invokingasynchronizedinstancemethodofanobjectacquiresalockontheobject.•Invokingasynchronizedstaticmethodofaclassacquiresalockontheclass.•Asynchronizedblockcanbeusedtoacquirealockonanyobject,notjustthisobject,whenexecutingablockofcode.synchronized(expr){statements;}•exprmustevaluatetoanobjectreference.•Iftheobjectisalreadylockedbyanotherthread,thethreadisblockeduntilthelockisreleased.•Whenalockisobtainedontheobject,thestatementsinthesynchronizedblockareexecuted,andthenthelockisreleased.1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
SynchronizingStatementsvs.MethodsAnysynchronizedinstancemethodcanbeconvertedintoasynchronizedstatement.Supposethatthefollowingisasynchronizedinstancemethod:publicsynchronizedvoidxMethod(){//methodbody}ThismethodisequivalenttopublicvoidxMethod(){synchronized(this){//methodbody}}1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Same as ReentrantLock(false).
Creates a lock with the given fairness policy. When the fairness is true, the longest-waiting thread will get the lock. Otherwise, there is no particular access order. "interface» java.util.concurrent.locks.Lock +lock(): void +unlock(): void +newCondition(): ConditionAcquires the lock.
Releases the lock.
Returns a new Condition instance that is bound to thisLock instance.
java.util.concurrent.locks.ReentrantLock +ReentrantLock() +ReentrantLock(fair: boolean)1.ThreadsConcurrency-SynchronizationusingLocksLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
FairnessPolicy•ReentrantLock:concreteimplementationofLockforcreatingmutuallyexclusivelocks.•Createalockwiththespecifiedfairnesspolicy.•Truefairnesspoliciesguaranteethelongest-waitthreadtoobtainthelockfirst.•Falsefairnesspoliciesgrantalocktoawaitingthreadwithoutanyaccessorder.•Programsusingfairlocksaccessedbymanythreadsmayhavepooroverallperformancethanthoseusingthedefaultsetting,buthavesmallervariancesintimestoobtainlocksandguaranteelackofstarvation.1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Example:UsingLocksThisexamplerevisesAccountWithoutSync.javainAccountWithoutSyncUsingLock.javatosynchronizetheaccountmodificationusingexplicitlocks.1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
"interface» java.util.concurrent.Condition +await(): void +signal(): void +signalAll(): Condition Causes the current thread to wait until the condition is signaled.Wakes up one waiting thread.
Wakes up all waiting threads.
1.ThreadsConcurrency-SynchronizationLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
while (balance < withdrawAmount) newDeposit.await();Withdraw Task
-char token +getToken +setToken +paintComponet +mouseClicked balance -= withdrawAmount -char token +getToken +setToken lock.unlock();Deposit Task
-char token +getToken +setToken +paintComponet +mouseClicked lock.lock(); -char token +getToken +setToken +paintComponet +mouseClicked newDeposit.signalAll(); balance += depositAmount -char token +getToken +setToken +paintComponet +mouseClicked lock.unlock(); -char token lock.lock(); -char token +getToken +setToken +paintComponet +mouseClickedLiang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Example:ThreadCooperationWriteaprogramthatdemonstratesthreadcooperation(ThreadCooperation.java).Supposethatyoucreateandlaunchtwothreads,onedepositstoanaccount,andtheotherwithdrawsfromthesameaccount.Thesecondthreadhastowaitiftheamounttobewithdrawnismorethanthecurrentbalanceintheaccount.Whenevernewfundisdepositedtotheaccount,thefirstthreadnotifiesthesecondthreadtoresume.Iftheamountisstillnotenoughforawithdrawal,thesecondthreadhastocontinuetowaitformorefundintheaccount.Assumetheinitialbalanceis0andtheamounttodepositandtowithdrawisrandomlygenerated.Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 01360126711.ThreadsCooperation
Java'sBuilt-inMonitors•LocksandconditionsarenewstartingwithJava5.•PriortoJava5,threadcommunicationswereprogrammedusingobject'sbuilt-inmonitors.•Locksandconditionsaremorepowerfulandflexiblethanthebuilt-inmonitor.•Amonitorisanobjectwithmutualexclusionandsynchronizationcapabilities.•Onlyonethreadcanexecuteamethodatatimeinthemonitor.•Athreadentersthemonitorbyacquiringalock(synchronizedkeywordonmethod/block)onthemonitorandexitsbyreleasingthelock.•Athreadcanwaitinamonitoriftheconditionisnotrightforittocontinueexecutinginthemonitor.•Anyobjectcanbeamonitor.Anobjectbecomesamonitoronceathreadlocksit.Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 01360126711.ThreadsSynchronization-Monitors
wait(),notify(),andnotifyAll()Usethewait(),notify(),andnotifyAll()methodstofacilitatecommunicationamongthreads.Thewait(),notify(),andnotifyAll()methodsmustbecalledinasynchronizedmethodorasynchronizedblockonthecallingobjectofthesemethods.Otherwise,anIllegalMonitorStateExceptionwouldoccur.Thewait()methodletsthethreadwaituntilsomeconditionoccurs.Whenitoccurs,youcanusethenotify()ornotifyAll()methodstonotifythewaitingthreadstoresumenormalexecution.ThenotifyAll()methodwakesupallwaitingthreads,whilenotify()picksuponlyonethreadfromawaitingqueue.Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 01360126711.ThreadsSynchronization-Monitors
synchronized (anObject) { try { // Wait for the condition to become true while (!condition) anObject.wait(); // Do something when condition is true catch (InterruptedException ex) { ex.printStackTrace();