information · java threads execute at the same speed because each thread is assigned to its own...
TRANSCRIPT
INF2440-V18
1/8
InformationINF2440Spring2018writtenexamDateandtime:June11th,2018at09:00.Duration:4hoursMaterialallowed:Allwrittenmaterialisallowed.Noelectronicaidisallowed.ThelectureslidesareattachedasaPDF.
1 Question1.1:JavaThreadCreationInaJavaprogram,theprogrammermustcreateandstarteverythreadthattheprogramuses.Isthisright?Selectanalternative:
Yes,theprogrammustcreateandstartallthreads.
Yes,theprogrammustcreateandstartallthreadsinmain().
No,thefirstthreadiscreatedautomaticallyandisautomaticallystartedandsettoexecutethemain()method.Theremainingthreadsmustbecreatedandstartedbyoneoftheotherthreadsintheprogram.
No,theprogrammermustmerelyprovidethecodeforthethreads.Thecompilerwillthenautomaticallygeneratethethreadsatcompiletimeandensurethattheyarestartedwhentheprogramruns.
No,allthreadsarestartedautomatically.
Maximummarks:4
2 Question1.2:JavaThreadsFeaturesWhichofthefollowingstatementsaretrueforJavaThreadsthatarecreatedinthesameprogram?(Morethanoneanswerispossible.)Selectoneormorealternatives:
Javathreadscanexecuteinparallelindependentlyofoneanotheronmulti-coremachines.
Iftherearemorethreadsthanavailablecores,theprogramcannotberun.
Javathreadsexecuteatthesamespeedbecauseeachthreadisassignedtoitsowncore.
Javathreadscanaccessthelocalvariableofoneanother.
Javathreadsresideinacommonpartofmemoryandcanaccessstaticvariablesdeclaredintheclasscontainingthethreads.
Javathreadsalwaysexecuteoneatatime.
Maximummarks:6
3 Question1.3:JavaSynchronizedCanweensurethatonlyonethreadatatimeisexecutingamethodbyprefixingthemethodwiththe
INF2440-V18
2/8
synchronizedkeyword.Selectanalternative:
Yes,ifmorethanonethreadcallsthemethod,theJavasystemensuresthatonlyonethreadisexecutingthemethodatatime.
Yes,exceptfortheinitialthreadrunningmain()--itisalwaysallowedtoexecutethemethodevenifanotherthreadisrunningthemethodatthesametime.
No,insidethemethod,wemustaddasynchronizationofsomekind,e.g.,CyclicBarrier.
Onlyifthemethodreturntypeisvoid.
Maximummarks:5
4 Question1.4:PerformanceofJavaThreadsWhichofthefollowingstatementsisclosesttoreality?Selectanalternative:
Javathreadscanbecreatedandrunsoquicklythatevenifwearejustdoingtwoorthreeintegeradditions,itisworthdoingtheminaseparatethreadbecausethethreadwillexecutequicklyonanothercore.
Javathreadstakealotoftimetocreateandtosynchronizesoingeneralathreadshouldnotbecreatedunlessitcandoalotofwork,e.g.,atleastmanythousandsofadditions.
JavaThreadsarecheaptocreateaslongastherearelessthreadsthancoresonthemachine.
Javathreadsareexpensivetocreatebutitbecomescheaperandcheapertocreatethreadsthemorethreadsaprogramcreates.
Maximummarks:5
Question2:CyclicBarriersInthisquestion,youshouldconsidertheprogramProblem.javaattachedasaPDF-document.
5 Question2.1:CyclicBarrier-terminationwithtwothreadsWhentheprogramiscalledwiththeparameters"20",willtheprogramalwaysterminate?Explainyouranswer.
Fillinyouranswerhere
INF2440-V18
3/8
Fillinyouranswerhere
Words:0
Maximummarks:10
6 Question2.2:CyclicBarrier-outputwithtwothreadsWhentheprogramiscalledwiththeparameters"20",willtheprogramalwaysprintthesametext?Explainyouranswer.Fillinyouranswerhere
Words:0
Maximummarks:10
7 Question2.3CyclicBarrier:TerminationwithfourthreadsWhentheprogramiscalledwiththeparameters"22",willtheprogramalwaysterminate?Explainyouranswer.
Fillinyouranswerhere
INF2440-V18
4/8
Fillinyouranswerhere
Words:0
Maximummarks:12
8 Question2.4:CyclicBarrier:OutputwithfourthreadsWhentheprogramiscalledwiththeparamters"22",willtheprogramalwaysprintthesametext?Ifso,showtheoutput.Ifnot,givetwodifferentexamplesofwhattheprogramprints.Fillinyouranswerhere
Words:0
Maximummarks:12
Question3:FindingPrimeDesertsThisquestionisbasedonErathostenesSievethatfindsprimenumbersuptoagivennumberN.YoushouldalreadybequitefamiliarwiththesieveasyouhaveimplementeditinOblig3(attachedasPDF).Thisquestionisaboutfindingso-calledPrimeDeserts.APrimeDesertisaninterval[A,B]whereA<B,AandB
INF2440-V18
5/8
areprimenumbers,andthereisnoprimebetweenAandB.Examplesofsuchdesertsare[2,3],[7,11],[23,29],and[337,347].ThesizeofaPrimeDesertisdefinedasB-A-1,i.e.,thenumberofintegersstrictlybetweenAandB.AiscalledthestartpointofthePrimeDesertandBiscalledtheendpoint.YouaretowriteaJavaprogramthatgeneratesalistofPrimeDeserts.Thelistshouldbesortedsothattheintervalscomeinascendingorder,i.e.,thestartspointsareinascendingorder.ThefirstPrimeDesertis[2,3]andthereafter,thenextPrimeDesertshouldbelargerthanthepreviousonethroughoutthelist.Furthermore,youshouldfindallPrimeDesertswheretheendpointnogreaterthanN,butyoushouldexcludefromthelistanyPrimeDesertwhosesizeisnotgreaterthanthesizeofthepreviousPrimeDesertinthelist.Forexample,thatmeansthatthestartofthelistis:[2,3],[3,5],[7,11],[23,29],[89,97],...i.e.,[5,7],[11,13],[13,17],[17,19]andmoreareleftoutbecausetheirsizeisnotgreaterthanthepreviousPrimeDesertinthelist.Tobesure,youmaynotleaveoutaPrimeDesert,ifitislargerthanthepreviousinthelistandsmallerthanthenextone;forexample,youcannothavealistthatstartswith[2,3]followedby[23,29].YouneednotwritetheentireprogramasyoucanassumethatyoualreadyhavethecodethatyouwroteforOblig3.YouarewelcometobaseyourcodeonModell2fromthelecturesinWeek5(uke5).
9 Question3.1:SequentialProgramforfindingPrimeDesertsWriteasequentialJavaprogramthatfindsthelistofPrimeDesertsspecifiedintheintroductiontoQuestion3.Fillinyouranswerhere
Maximummarks:20
10 Question3.2:ParallelProgramtofindPrimeDesertsWriteaparallelJavaprogramthatfindsthelistofPrimeDesertsspecifiedintheintroductiontoQuestion3.Strivetoachieveaspeedupoverthesequentialversion.
Fillinyouranswerhere
1
INF2440-V18
6/8
Fillinyouranswerhere
Maximummarks:40
Question4:BubblesortBubblesortisasortingalgorithmthatsorts,e.g.,anintegerarrayA,bycomparingtwoneighboringelementsandexchaningthem,ifthefirstoneisgreaterthanthesecond.Thesortingconsistsofanumberofpasses.Eachpassgoesthruthearrayoneelementatatimeandperformstheexchange,ifnecessary.Attheendofpassk,thek'thlargestnumberisinplaceatthetopofthearray,sothenextpassneednotconsiderthetopkelementsofthearray.AsequentialbubblesortofanintegerarrayisgivenasaPDFfile.
11 Question4.1ParallelizingBubblesortHowcanBubblesortbeparallelized?Describethedesignofasolution.
Fillinyouranswerhere
1
INF2440-V18
7/8
Fillinyouranswerhere
Words:0
Maximummarks:20
12 Question4.2:ParallelBubblesortWriteaJavaprogramimplementingyourdesignofaparallelversionofBubblesortfromQuestion4.1.Strivetohaveaspeedupoverthesequentialversion.Putanyaddedexplanationthatyouhaveascommentsinthecode.Fillinyouranswerhere
Maximummarks:40
13 Question5.1:RecursionandParallelismTherearemanywaysofparallelizingarecurvisealgorithm.Ofthefollowingstatements,whichofthemisagoodidea(youmayselectmorethanone):
Selectoneormorealternatives:
1
INF2440-V18
8/8
Selectoneormorealternatives:
Whentherecursivecallsformatreestructure,itisagoodideatospawnandusethreadsatthebottomofthetreeonly.
Asimplewaytoparallelizearecursiveprogramistohaveonethreadperrecursivecall.Thisalmostalwaysleadstoachievingagoodspeedup.
Itisimportanttolimitthenumberofthreads.
Whentherecursivecallsformatreestructure,itisagoodideatospawnnewthreadatthetopofthetreeandlimitthenumberofthreadsatthebottomofthetree.
Recursivecallsarerelativelyexpensivecomparedtocreatingandrunningathread.
Recursivecallsareseveralordersofmagnitudecheaperthancreatingandrunningathread.
Whentherecursivecallsformatreestructure,itisagoodideatoreplacebranchesatthelowerlevelsofthetreewithsimplesequentialsolutionsoftheproblem.
Itisimportanttobalancethenumberofthreadsandtheamountofworkdonebyeachthread.
Maximummarks:16
Question 12Attached
static void bubbleSort(int[] arr) { int n = arr.length; int temp; for (int i=0; i < n; i++){ for (int j=1; j < (n-i); j++){ if(arr[j-1] > arr[j]){ //swap elements temp = arr[j-1]; arr[j-1] = arr[j]; arr[j] = temp; } } } }
1
Question 12Attached
static void bubbleSort(int[] arr) { int n = arr.length; int temp; for (int i=0; i < n; i++){ for (int j=1; j < (n-i); j++){ if(arr[j-1] > arr[j]){ //swap elements temp = arr[j-1]; arr[j-1] = arr[j]; arr[j] = temp; } } } }
1
Question 5Attached
Problem-javaimport java.util.concurrent.*; class Problem { // felles data og metoder A static int num = 2; static int extra = 2; static CyclicBarrier b;
public static void main(String [] args) { Problem p = new Problem(); num = Integer.parseInt(args[0]); extra = Integer.parseInt(args[1]); b = new CyclicBarrier(num); p.utfoer(num+extra); // extra threads System.out.println(" Main TERMINATED"); } // end main
void utfoer (int antT) { Thread [] t = new Thread [antT]; for (int i =0; i< antT; i++) ( t[i] = new Thread(new Arbeider(i))).start(); try { for (int i =0; i< antT; i++) t[i].join(); } catch(Exception e) {} } // end utfoer
class Arbeider implements Runnable { // lokale data og metoder B int ind;
void sync() { try{ b.await(); } catch (Exception e) { return;} }
public Arbeider (int in) {ind = in;};
public void run() { sync(); System.out.println("A"+ind); sync(); System.out.println("B"+ind); } // end run } // end indre klasse Arbeider } // end class Problem
Page 1
Question 5Attached
Problem-javaimport java.util.concurrent.*; class Problem { // felles data og metoder A static int num = 2; static int extra = 2; static CyclicBarrier b;
public static void main(String [] args) { Problem p = new Problem(); num = Integer.parseInt(args[0]); extra = Integer.parseInt(args[1]); b = new CyclicBarrier(num); p.utfoer(num+extra); // extra threads System.out.println(" Main TERMINATED"); } // end main
void utfoer (int antT) { Thread [] t = new Thread [antT]; for (int i =0; i< antT; i++) ( t[i] = new Thread(new Arbeider(i))).start(); try { for (int i =0; i< antT; i++) t[i].join(); } catch(Exception e) {} } // end utfoer
class Arbeider implements Runnable { // lokale data og metoder B int ind;
void sync() { try{ b.await(); } catch (Exception e) { return;} }
public Arbeider (int in) {ind = in;};
public void run() { sync(); System.out.println("A"+ind); sync(); System.out.println("B"+ind); } // end run } // end indre klasse Arbeider } // end class Problem
Page 1
Question 6Attached
Problem-javaimport java.util.concurrent.*; class Problem { // felles data og metoder A static int num = 2; static int extra = 2; static CyclicBarrier b;
public static void main(String [] args) { Problem p = new Problem(); num = Integer.parseInt(args[0]); extra = Integer.parseInt(args[1]); b = new CyclicBarrier(num); p.utfoer(num+extra); // extra threads System.out.println(" Main TERMINATED"); } // end main
void utfoer (int antT) { Thread [] t = new Thread [antT]; for (int i =0; i< antT; i++) ( t[i] = new Thread(new Arbeider(i))).start(); try { for (int i =0; i< antT; i++) t[i].join(); } catch(Exception e) {} } // end utfoer
class Arbeider implements Runnable { // lokale data og metoder B int ind;
void sync() { try{ b.await(); } catch (Exception e) { return;} }
public Arbeider (int in) {ind = in;};
public void run() { sync(); System.out.println("A"+ind); sync(); System.out.println("B"+ind); } // end run } // end indre klasse Arbeider } // end class Problem
Page 1
Question 6Attached
Problem-javaimport java.util.concurrent.*; class Problem { // felles data og metoder A static int num = 2; static int extra = 2; static CyclicBarrier b;
public static void main(String [] args) { Problem p = new Problem(); num = Integer.parseInt(args[0]); extra = Integer.parseInt(args[1]); b = new CyclicBarrier(num); p.utfoer(num+extra); // extra threads System.out.println(" Main TERMINATED"); } // end main
void utfoer (int antT) { Thread [] t = new Thread [antT]; for (int i =0; i< antT; i++) ( t[i] = new Thread(new Arbeider(i))).start(); try { for (int i =0; i< antT; i++) t[i].join(); } catch(Exception e) {} } // end utfoer
class Arbeider implements Runnable { // lokale data og metoder B int ind;
void sync() { try{ b.await(); } catch (Exception e) { return;} }
public Arbeider (int in) {ind = in;};
public void run() { sync(); System.out.println("A"+ind); sync(); System.out.println("B"+ind); } // end run } // end indre klasse Arbeider } // end class Problem
Page 1
Question 7Attached
Problem-javaimport java.util.concurrent.*; class Problem { // felles data og metoder A static int num = 2; static int extra = 2; static CyclicBarrier b;
public static void main(String [] args) { Problem p = new Problem(); num = Integer.parseInt(args[0]); extra = Integer.parseInt(args[1]); b = new CyclicBarrier(num); p.utfoer(num+extra); // extra threads System.out.println(" Main TERMINATED"); } // end main
void utfoer (int antT) { Thread [] t = new Thread [antT]; for (int i =0; i< antT; i++) ( t[i] = new Thread(new Arbeider(i))).start(); try { for (int i =0; i< antT; i++) t[i].join(); } catch(Exception e) {} } // end utfoer
class Arbeider implements Runnable { // lokale data og metoder B int ind;
void sync() { try{ b.await(); } catch (Exception e) { return;} }
public Arbeider (int in) {ind = in;};
public void run() { sync(); System.out.println("A"+ind); sync(); System.out.println("B"+ind); } // end run } // end indre klasse Arbeider } // end class Problem
Page 1
Question 7Attached
Problem-javaimport java.util.concurrent.*; class Problem { // felles data og metoder A static int num = 2; static int extra = 2; static CyclicBarrier b;
public static void main(String [] args) { Problem p = new Problem(); num = Integer.parseInt(args[0]); extra = Integer.parseInt(args[1]); b = new CyclicBarrier(num); p.utfoer(num+extra); // extra threads System.out.println(" Main TERMINATED"); } // end main
void utfoer (int antT) { Thread [] t = new Thread [antT]; for (int i =0; i< antT; i++) ( t[i] = new Thread(new Arbeider(i))).start(); try { for (int i =0; i< antT; i++) t[i].join(); } catch(Exception e) {} } // end utfoer
class Arbeider implements Runnable { // lokale data og metoder B int ind;
void sync() { try{ b.await(); } catch (Exception e) { return;} }
public Arbeider (int in) {ind = in;};
public void run() { sync(); System.out.println("A"+ind); sync(); System.out.println("B"+ind); } // end run } // end indre klasse Arbeider } // end class Problem
Page 1
Question 8Attached
Problem-javaimport java.util.concurrent.*; class Problem { // felles data og metoder A static int num = 2; static int extra = 2; static CyclicBarrier b;
public static void main(String [] args) { Problem p = new Problem(); num = Integer.parseInt(args[0]); extra = Integer.parseInt(args[1]); b = new CyclicBarrier(num); p.utfoer(num+extra); // extra threads System.out.println(" Main TERMINATED"); } // end main
void utfoer (int antT) { Thread [] t = new Thread [antT]; for (int i =0; i< antT; i++) ( t[i] = new Thread(new Arbeider(i))).start(); try { for (int i =0; i< antT; i++) t[i].join(); } catch(Exception e) {} } // end utfoer
class Arbeider implements Runnable { // lokale data og metoder B int ind;
void sync() { try{ b.await(); } catch (Exception e) { return;} }
public Arbeider (int in) {ind = in;};
public void run() { sync(); System.out.println("A"+ind); sync(); System.out.println("B"+ind); } // end run } // end indre klasse Arbeider } // end class Problem
Page 1
Question 8Attached
Problem-javaimport java.util.concurrent.*; class Problem { // felles data og metoder A static int num = 2; static int extra = 2; static CyclicBarrier b;
public static void main(String [] args) { Problem p = new Problem(); num = Integer.parseInt(args[0]); extra = Integer.parseInt(args[1]); b = new CyclicBarrier(num); p.utfoer(num+extra); // extra threads System.out.println(" Main TERMINATED"); } // end main
void utfoer (int antT) { Thread [] t = new Thread [antT]; for (int i =0; i< antT; i++) ( t[i] = new Thread(new Arbeider(i))).start(); try { for (int i =0; i< antT; i++) t[i].join(); } catch(Exception e) {} } // end utfoer
class Arbeider implements Runnable { // lokale data og metoder B int ind;
void sync() { try{ b.await(); } catch (Exception e) { return;} }
public Arbeider (int in) {ind = in;};
public void run() { sync(); System.out.println("A"+ind); sync(); System.out.println("B"+ind); } // end run } // end indre klasse Arbeider } // end class Problem
Page 1