Information · Java threads execute at the same speed because each thread is assigned to its own...

28
INF2440-V18 1/8 Information INF2440 Spring 2018 written exam Date and time: June 11th, 2018 at 09:00. Duration: 4 hours Material allowed: All written material is allowed. No electronic aid is allowed. The lecture slides are attached as a PDF. 1 Question 1.1: Java Thread Creation In a Java program, the programmer must create and start every thread that the program uses. Is this right? Select an alternative: Yes, the program must create and start all threads. Yes, the program must create and start all threads in main(). No, the first thread is created automatically and is automatically started and set to execute the main() method. The remaining threads must be created and started by one of the other threads in the program. No, the programmer must merely provide the code for the threads. The compiler will then automatically generate the threads at compile time and ensure that they are started when the program runs. No, all threads are started automatically. Maximum marks: 4 2 Question 1.2: Java Threads Features Which of the following statements are true for Java Threads that are created in the same program? (More than one answer is possible.) Select one or more alternatives: Java threads can execute in parallel independently of one another on multi-core machines. If there are more threads than available cores, the program cannot be run. Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside in a common part of memory and can access static variables declared in the class containing the threads. Java threads always execute one at a time. Maximum marks: 6 3 Question 1.3: Java Synchronized Can we ensure that only one thread at a time is executing a method by prefixing the method with the

Transcript of Information · Java threads execute at the same speed because each thread is assigned to its own...

Page 1: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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

Page 2: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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

Page 3: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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

Page 4: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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

Page 5: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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

Page 6: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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

Page 7: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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

Page 8: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

INF2440-V18

8/8

Selectoneormorealternatives:

Whentherecursivecallsformatreestructure,itisagoodideatospawnandusethreadsatthebottomofthetreeonly.

Asimplewaytoparallelizearecursiveprogramistohaveonethreadperrecursivecall.Thisalmostalwaysleadstoachievingagoodspeedup.

Itisimportanttolimitthenumberofthreads.

Whentherecursivecallsformatreestructure,itisagoodideatospawnnewthreadatthetopofthetreeandlimitthenumberofthreadsatthebottomofthetree.

Recursivecallsarerelativelyexpensivecomparedtocreatingandrunningathread.

Recursivecallsareseveralordersofmagnitudecheaperthancreatingandrunningathread.

Whentherecursivecallsformatreestructure,itisagoodideatoreplacebranchesatthelowerlevelsofthetreewithsimplesequentialsolutionsoftheproblem.

Itisimportanttobalancethenumberofthreadsandtheamountofworkdonebyeachthread.

Maximummarks:16

Page 9: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

Question 12Attached

Page 10: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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

Page 11: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

Question 12Attached

Page 12: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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

Page 13: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

Question 5Attached

Page 14: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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

Page 15: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

Question 5Attached

Page 16: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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

Page 17: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

Question 6Attached

Page 18: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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

Page 19: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

Question 6Attached

Page 20: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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

Page 21: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

Question 7Attached

Page 22: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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

Page 23: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

Question 7Attached

Page 24: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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

Page 25: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

Question 8Attached

Page 26: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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

Page 27: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

Question 8Attached

Page 28: Information · Java threads execute at the same speed because each thread is assigned to its own core . Java threads can access the local variable of one another. Java threads reside

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