Java - Multithreading
Java is amulti threaded programming language which means we can develop multi threaded program using Java. A multi threaded program contains two or more
Unit 4: MultiThreading
Multithreaded Program. A unique property of the java is that it supports the multithreading. Java enables us the multiple flows of control in developing the
Multithreading in Java
multiple threads simultaneously. ▷ Thread is basically a lightweight sub-process a smallest unit of processing. Page 4. Advantages of Java Multithreading. 1
Advance praise for - Java Concurrency in Practice
Java Concurrency in Practice provides you with the concepts and techniques multithreaded Java programs. If you've ever had to synchronize a method and ...
Multithreading
However for more intricate sys- tem-level programming
Advanced-java.pdf
In this tutorial we are going to cover advanced Java concepts assuming that our readers already have some basic knowledge of multithreaded programming in ...
[PDF] Java Tutorial in PDF - Tutorialspoint
This tutorial has been prepared for the beginners to help them understand the basic to advanced concepts related to Java Programming language. Prerequisites.
Teach Yourself Java in 21 Days
Multithreading. 353. The Problem with Parallelism ... advanced Java programming however
Multithreaded Programming using Java Threads Agenda
▫ Java Threads and States. ▫. Priorities. ▫ Accessing Shared Resources. ▫. Synchronisation. ▫ Assignment 1: ▫. Multi-Threaded Math Server. ▫ Advanced
Lecture 8 Java SE – Advanced Multithreading
Advanced Java. Multithreading. Java 8 Multi-. Threading with. Lambda. Exchange. Ideas. Page 4. Advanced Multi-Threading java.util.concurrent - Executor
Multithreading
tem-level programming we suggest that you turn to a more advanced reference
TutorialsPoint
This tutorial has been prepared for the beginners to help them understand the basic to advanced concepts related to Java Programming language. Prerequisites.
Java The Complete Reference Seventh Edition
Herbert Schildt is a leading authority on the. Java C
Multithreaded Programming using Java Threads Agenda
Java Threads and States. ?. Priorities. ? Accessing Shared Resources. ?. Synchronisation. ? Assignment 1: ?. Multi-Threaded Math Server. ? Advanced
Object-Oriented Programming Java
public class MyDate{ private int day = 26; private int month = 9; private int year = 2016; public MyDate( int day int month
Teach Yourself Java in 21 Days
multithreading and how to use it to allow different parts of your Java with more advanced concepts in putting together Java programs and working with ...
Advanced-java.pdf
In this tutorial we are going to cover advanced Java concepts assuming that leading to lower concurrency in a multithreaded environments (more details.
Java - Multithreading
JAVA - MULTITHREADING. Java is amulti threaded programming language which means we can develop multi threaded program using Java. A multi threaded program
Multithreaded Programming Guide
Oracle and Java are registered trademarks of Oracle and/or its affiliates. The concept of multithreaded programming goes back to at least the 1960s.
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();Task 1
synchronized (anObject) { // When condition becomes true anObject.notify(); or anObject.notifyAll();Task 2
resume1.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 +mouseClickedTask for adding an int
-char token +getToken +setToken +paintComponet +mouseClickedAdd an int to the buffer
-char tokenquotesdbs_dbs11.pdfusesText_17[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