17
J.E.D.I.  1 Java Threads  1.1 Objectives This chapter discusses Java threads. This includes synchronization commands as well as solutions to the synchronization problems discussed in a previous chapter.  1.2 Chapter Outline Creating a Java Thread Synchronized Keyword ait and !oti"y #igh $evel Concurrency %b&ects  1.3 Creating a Java Thread Java threads are a way to have di""erent parts o" your program running at the same time. 'or e(ample) you can create an application that accepts input "rom di""erent users at the same time) each user handled by a thread. *lso) most networ+ing applications involve threads, you would need to create a thread that would wait "or incoming messages while the rest o" your program handles your outgoing messages. This section discusses how to create &ava threads. There are two ways to create a Java thread) one is by e(tending the thread class) the other is by implementing the -unnable inter"ace. The run/ method o" a thread is its main method) thread e(ecution always starts "rom this method.  1.3.1 Extending the Thread class e will create a simple thread that simply prints out a number 011 times in a row. class MyThread extends Thread { int i; MyThread(in t i) { this.i = i; } public void run() { for (int ctr=0; ctr < 00; ctr!!) { "yste#.out.print(i); } } } To show the di""erence between parallel and non2parallel e(ecution) we have the "ollowing e(ecutable 3yThreadDemo class class MyThread$e#o { public static void #ain("trin% ar%s&') { MyThread t = ne MyThread(); MyThread t* = ne MyThread(*) ; MyThread t+ = ne MyThread(+) ; t.run(); t*.run(); %perating Systems 4

Teacher's Notes - Lab Chapter 5 - Java Threads

Embed Size (px)

Citation preview

Page 1: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 1/17

J.E.D.I.

 1 Java Threads

 1.1 ObjectivesThis chapter discusses Java threads. This includes synchronization commands as well assolutions to the synchronization problems discussed in a previous chapter.

 1.2 Chapter Outline● Creating a Java Thread

● Synchronized Keyword

● ait and !oti"y

#igh $evel Concurrency %b&ects

 1.3 Creating a Java ThreadJava threads are a way to have di""erent parts o" your program running at the same time. 'ore(ample) you can create an application that accepts input "rom di""erent users at the sametime) each user handled by a thread. *lso) most networ+ing applications involve threads, youwould need to create a thread that would wait "or incoming messages while the rest o" yourprogram handles your outgoing messages.

This section discusses how to create &ava threads. There are two ways to create a Java thread)one is by e(tending the thread class) the other is by implementing the -unnable inter"ace. The

run/ method o" a thread is its main method) thread e(ecution always starts "rom this method.

 1.3.1 Extending the Thread class

e will create a simple thread that simply prints out a number 011 times in a row.

class MyThread extends Thread {

int i;

MyThread(int i) {

this.i = i;

}

public void run() {

for (int ctr=0; ctr < 00; ctr!!) {

"yste#.out.print(i);

}

}

}

To show the di""erence between parallel and non2parallel e(ecution) we have the "ollowinge(ecutable 3yThreadDemo class

class MyThread$e#o {

public static void #ain("trin% ar%s&') {

MyThread t = ne MyThread();

MyThread t* = ne MyThread(*);

MyThread t+ = ne MyThread(+);

t.run();t*.run();

%perating Systems 4

Page 2: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 2/17

J.E.D.I.

t+.run();

"yste#.out.print(,Main ends,);

}}

5pon e(ecuting 3yThreadDemo) we will get output that loo+s li+e this

- ava MyThread$e#o

...********.....+++++......Main ends

*s can be seen) our program "irst e(ecuted t46s run method) which prints 011 consecutive 46s.*"ter that t76s run method) which prints consecutive 76s) and so on. 3ain ends appear at thelast part o" the output as it is the last part o" the program. !o multithreaded e(ecution

occurred.

To e(ecute these threads concurrently) we invo+e the built2in start/ method) instead o" calling

the run/ method directly.

class MyThread$e#o {

public static void #ain("trin% ar%s&') {

MyThread t = ne MyThread();

MyThread t* = ne MyThread(*);

MyThread t+ = ne MyThread(+);

t1.start();t*.start();

t+.start();

"yste#.out.print(,Main ends,);

}}

%perating Systems 7

Page 3: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 3/17

J.E.D.I.

%ur second thread demo would produce the "ollowing output.

- ava MyThread$e#o

**++**+***+++++Main ends+++***...

e can see that threads t4) t7 and t8 are all running at the same time as printing o" 46s and

76s and 86s are interspersed. 9ery interesting to note is the appearance o" the :3ain ends:string in the middle o" the output se;uence) which indicates that the main method has already"inished e(ecuting while thread 4) thread 7 and thread 8 are still running.

-unning a main method creates a thread. !ormally) your program ends when the main thread

ends. #owever) creating and then running a thread6s start method creates a whole new threadthat e(ecutes its run/ method independent o" the main method.

1.3.2 Implementing Runnable

*nother way to create a thread is to implement the -unnable inter"ace. This may be desired i"

your thread e(tends another class. <y e(tending another class) you will be unable to e(tendclass thread as Java classes can only e(tend a single class. #owever) a class can implementmore than one inter"ace.

The "ollowing is our 3yThread class created by implementing the runnable inter"ace. In

implementing the runnable inter"ace) you must de"ine the run/ method.

class MyThread implements Runnable {

... <thread body is #ostly the sa#e-

}

The main di""erence comes in instantiating 3yThread=

%perating Systems 8

Page 4: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 4/17

J.E.D.I.

Thread t = ne Thread(ne MyThread());

3yThread is passed as a parameter to the constructor o" a thread ob&ect.

1.3.3 Pausing ThreadsThreads can be paused by the sleep/ method. 'or e(ample) to have 3yThread pause "or hal" asecond be"ore it prints the ne(t number) we add the "ollowing lines o" code to our "or loop.

for (int ctr=0; ctr < 00; ctr!!) {

"yste#.out.print(i);

try {Thread.sleep(00); // 00 #iliseconds

} catch (nterrupted1xception e) { }

}

The sleep/ method is a static member o" the Thread class and can be invo+ed "rom anythread) including the main thread. 'or e(ample) i" we wanted to pause "or a second be"orestarting thread t7 in our main method) we could have=

public static void #ain("trin% ar%s&') {

...

t.start();

try {

Thread.sleep(000);

} catch (nterrupted1xception e) { }

t*.start();

 1.3.4 Joins

>ou can also ma+e a thread stop until another thread "inishes running by invo+ing a thread6s

 &oin/ method. 'or instance) to ma+e our main thread to stop running until thread t4 is"inished) we could simply say...

public static void #ain("trin% ar%s&') {

...

t.start();

try {t1.join();

} catch (InterruptedException e) { }t*.start();

This would ma+e t4 "inish running be"ore thread 7 is started.

1.4 Synchronized ey!ordIn this section ) we will "ind out how to implement a solution to the critical section problemusing Java. -ecall that only a single process can enter its critical section) all other processes

would have to wait. !o conte(t switching occurs inside a critical section.

Instead o" printing a continuous stream o" numbers) 3yThread calls a print41/ method in a

class 3y?rinter. print41/ prints 41 continuous numbers on a single line be"ore a newline.

%ur goal is to have these 41 continuous numbers printed without any conte(t switchesoccurring. In other words) our output should be=

  ...

%perating Systems @

Page 5: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 5/17

J.E.D.I.

**********

++++++++++

  ...

 1.4.1 Deining the solution

e will de"ine a class 3y?rinter that will have our print41/ method

class 3y?rinter Apublic void print41int value/ A

"or int i B 1, i 41, i/ ASystem.out.printvalue/,

System.out.println::/, FF newline a"ter 41 numbers

Instead o" printing numbers directly) we use the print41/ method in 3yThread as shown bythe "ollowing=

class 3yThread e(tends Thread Aint i,

"y#rinter p$3yThreadint i/ A

this.i B i,p % ne! "y#rinter&'$

public void run/ A"or int ctrB1, ctr 011, ctr/ A

p.print1(&i'$

'irst we will see the output o" &ust a single thread by commenting out the other threads=

class MyThread$e#o {

public static void #ain("trin% ar%s&') {

MyThread t = ne MyThread();

// MyThread t* = ne MyThread(*);

// MyThread t+ = ne MyThread(+);

t.start();

// t*.start();

// t+.start();

"yste#.out.print(,Main ends,);

}}

hen we run our 3yThreadDemo) we can see that the output matches what we want=

- ava MyThread$e#o

%perating Systems 0

Page 6: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 6/17

J.E.D.I.

  ...

#owever) running the other threads would give us output that loo+s li+e this=

- ava MyThread$e#o

*******

***+++++++*

...

e do not achieve our goal o" printing 41 consecutive numbers in a row as all three threads

are e(ecuting the print416s method at the same time. The end result is that we have morethan one number appearing on a single line.

There should not be a conte(t switch while we are printing 41 consecutive numbers. Thus) asolution to this problem is also a solution to the Critical Section ?roblem.

 1.4.2 !onitors in Ja"a

Java uses a monitor construct. %nly a single thread may run inside the monitor. To turn anob&ect into a monitor) simply put the synchronized +eyword on your method de"initions. %nly a

single thread can run any synchronized method in an ob&ect.

class My2rinter {

public synchroni3ed void print0(int value) {

for (int i = 0; i < 0; i!!) {

"yste#.out.print(value);}

"yste#.out.println(,,); // neline after 0 nu#bers

}

}

#owever) even i" we did turn our print41/ method into a synchronized method) it will still notwor+. To "ind out how to ma+e it wor+) we need to "irst "ind out how the synchronized +eywordwor+s.

Every ob&ect in Java has a loc+. hen a thread tries to run a synchronized method) it "irst tries

to get a loc+ on the ob&ect. I" it gets the loc+ then the thread runs the synchronized method) i"not) then it waits until the thread who owns the loc+ unloc+s it.

%perating Systems G

Page 7: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 7/17

J.E.D.I.

%ur e(ample does not wor+ because each thread has its own copy o" the 3y?rinter ob&ect.

class MyThread extends Thread {

int i;

My2rinter p;

MyThread(int i) {

this.i = i; p = ne !y"rinter(); ## each !y$hread creates its on !y"rinter%

}

public void run() {

for (int ctr=0; ctr < 00; ctr!!) {

p.print0(i);

}

}

}

%ur ob&ect diagram would loo+ li+e the one below. *s we can see) each thread owns its ownloc+ thus all o" them can run the synchronized method

* proper solution only gives one copy o" a 3y?rinter ob&ect to all threads.

%perating Systems H

Page 8: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 8/17

J.E.D.I.

* way to visualize it is that all Java ob&ects can be doors. * thread tries to see i" the door is

open. %nce the thread goes through the door) it loc+s it behind it. !o other threads can enterthe door because our "irst thread has loc+ed it "rom the inside. %ther threads can enter i" the

thread inside unloc+s the door and goes out. $ining up will only occur i" everyone only has asingle door to the critical region

*gain) only a single thread can run any synchronized method in an ob&ect. I" an ob&ect has asynchronized method and a regular method) only one thread can run the synchronized method

while multiple threads can run the regular method. Threads that you want to havesynchronized must share the same monitor ob&ect. -unning 3yThreadDemo now correctly

shows synchronized methods at wor+.

1.4.3 #$nchroni%ed bloc&s

*side "rom synchronized methods) Java also allows "or synchronized bloc+s. >ou must speci"y

what ob&ect the intrinsic loc+ comes "rom. Synchronized bloc+s allow "or "le(ibility) in the casei" we want our intrinsic loc+ to come "rom an ob&ect other than the current ob&ect. *lso) we can

have parts o" a method having a di""erent loc+ than others.

Consider the "ollowing modi"ied 3y?rinter class

class My2rinter {

4bect loc5 = ne 4bect();

4bect loc5* = ne 4bect();

public void print0(int value) {

synchroni3ed(loc5) {

for (int i = 0; i < 0; i!!) {

"yste#.out.print(value);

}

"yste#.out.println(,,); // neline after 0 nu#bers

}

}

public int s6uareMe(int i) {

synchroni3ed (loc5*) {

return i 7 i;

}

}

}

%nly one thread can run inside the synchronized bloc+ o" print41/ and s;uare3e/. #owever)two di""erent threads can be running in both synchronized bloc+s at the same time as we usedi""erent loc+s "or the two o" them as they don6t really inter"ere with one another/.

Synchronized bloc+s would also allow other parts o" a method to be run in parallel with others)

%perating Systems

Page 9: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 9/17

J.E.D.I.

as shown by the "ollowing diagram.

1.) *ait and +oti,y

 1.'.1 Producer(consumer problem

*t this stage) we can already implement some solutions to our synchronization problems.

#ere) we will now discuss a solution to the ?roducer2Consumer problem. Instead o" using beer)the producer will store in a shared array a random integer value which will be retrieved by theconsumer process. 'or discussion purposes) we will assume that the array can store a very

large number o" integers. The ?roducer will attempt to produce 411 integers in total.

'irst) we create a class that would store our shared variables. e have discussed be"ore thatwe do not want insert9alue/ and get9alue/ to run at the same time so we convert these tosynchronized methods and ma+e sure that both Consumer and ?roducer get the same

Shared9ars ob&ect.

class "hared8ars {

int array&' = ne int&0000';

int top;

// #ethod for insertin% a value

%perating Systems

Page 10: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 10/17

J.E.D.I.

public synchron3ed void insert8alue(int value) {

if (top < array.len%th) {

array&top' = value;

top!!;

}

}

// #ethod for %ettin% a value

public synchron3ied int %et8alue() {

if (top - 0) {

top99;

return array&top';

}

else

return 9;

}

}

!e(t) we de"ine our ?roducer class as such.

class 2roducer extends Thread {"hared8ars sv;

2roducer("hared8ars sv) {

// 2roducer:s reference to the "hared8ars obect created in #ain

this.sv = sv;

}

public void run() {

for (int i = 0; i < 00; i!!) {

// assi%nin% a rando# nu#ber fro# 0 to *00

int value = (int)(Math.rando#() 7 *00);

"yste#.out.println(,2roducer inserts , ! value);

sv.insert8alue(value);

try {

// ait a rando# a#ount of ti#e before insertin% a%ainThread.sleep((int)(Math.rando#() 7 0000));

} catch (nterrupted1xception e) { }

}

}

}

'or our consumer thread) we have the "ollowing code=

class onsu#er extends Thread {

"hared8ars sv;

onsu#er("hared8ars sv) {

// onsu#er:s reference to the "hared8ars obect created in #ain

this.sv = sv;

}

public void run() {

for (int i = 0; i < 00; i!!) {

int value = sv.%et8alue();

"yste#.out.println(,onsu#er %ot, ! value);

try {

// ait a rando# a#ount of ti#e before %ettin% a%ain

Thread.sleep((int)(Math.rando#() 7 0000));

}catch (nterrupted1xception e) { }

}

}

}

%ur main class would loo+ li+e this=

class 2roduceronsu#er$e#o {public static void #ain("trin% ar%s&') {

%perating Systems 41

Page 11: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 11/17

J.E.D.I.

"hared8ars sv = ne "hared8ars();

2roducer p = ne 2roducer(sv);

onsu#er c = ne onsu#er(sv);

p.start();

c.start();

}}

The output o" this code would be an orderly se;uence o" output=

2roducer inserts value

onsu#er %ot

onsu#er %ot 9

2roducer inserts value 0

2roducer inserts value

onsu#er %ot

...

!otice that) i" we try to get a value "rom the array and there isn6t any) we return a value 24.

>ou can see this clearly i" you increase the ?roducer delay to 41s) which means the ?roduceradds a value every 41s) consumer gets one every 0s. *t some point in time) the consumer

would get "rom an empty array.

ouldn6t it be better i" we have our Consumer wait "or the ?roducer to produce something

instead o" &ust getting 24

 1.'.2 )ait method 

The wait/ method) de"ined in class %b&ect and there"ore inherited by all ob&ects will cause thethread invo+ing wait/ to suspend itsel". #owever) a thread invo+ing wait/ must own theintrinsic loc+ o" the ob&ect it is calling wait/ "rom. I" we are going to call this.wait/ it has to be

in synchronizedthis/ bloc+

*lso) as with all methods that suspend thread e(ecution) li+e &oin/ and sleep/) our wait/method must be in a try2catch bloc+ that catches InterruptedE(ceptions.

The "ollowing code shows our modi"ication o" the get9alue/ method in class Shared9ars=

// called by onsu#er thread

public int %et8alue() {

synchroni3ed(this) {

if (top <= 0) {

try {

this.ait();

} catch (nterrupted1xception e) { }

}

top99;return array&top';

}}

%perating Systems 44

Page 12: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 12/17

J.E.D.I.

 1.'.3 *oti$ method 

*ll threads that call wait/ on an ob&ect are placed in a pool o" waiting threads "or that ob&ect.E(ecution resumes when another thread calls the noti"y/ method o" the ob&ect our "irst threadis waiting on.

'or our e(ample) our producer thread) a"ter inserting on an empty array) would noti"y the

consumer thread that it has placed a value in our array by calling the noti"y/ method on theShared9ars ob&ect. -ecall that ?roducer and Consumer both have a re"erence to the same

Shared9ars ob&ect.

The producer calling noti"y/ "rom insert9alue/ would in"orm any the consumer waiting on the

same Shared9ar ob&ect.

The "ollowing is our ne insert9alue/ method

// called by producer

public void insert8alue(int value) {

synchroni3ed(this) {

if (top < array.len%th) {

array&top' = value;

top!!;

if (top == ) { // insert on an e#pty array

%perating Systems 47

Page 13: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 13/17

J.E.D.I.

this.notify(); // notify sleepin% thread

}

}

}

}

hen the noti"y/ method o" an ob&ect is called) then a single waiting thread on that ob&ect is

signaled to get ready to resume e(ecution.

*"ter our ?roducer thread e(ists insert9alue and releases the loc+) our Consumer thread gets

the loc+ once again and resumes its e(ecution.

I" you run the demo program again) you can see that) even i" the producer is slow) the

consumer waits until the producer gives out a value be"ore getting that value. !ote that youmust also consider inserting on a "ull array. ?roducer must wait until consumer has ta+en awaysome values be"ore inserting.

e will leave the implementation o" this as an e(ercise.

 1.- igh level concurrency objectsThe methods discussed have been de"ined in Java "rom the very start. Since Java 4.0)additional classes have been added in the &ava.util.concurrent pac+age that assist in thecreation and manipulation o" threads. e will discuss these in passing in this section.

%perating Systems 48

Page 14: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 14/17

J.E.D.I.

 1.+.1 ,oc& -bects

*ny ob&ect in Java can be used as a loc+ "or synchronization. #owever) the &ava.util.concurrent.loc+s pac+age de"ines classes that have additional loc+ing "eatures. Thebasic inter"ace o" this pac+age is the $oc+ inter"ace.

*n ob&ect o" type $oc+ can only be owned by a single thread at a time. To ac;uire a loc+) athread must call its loc+/ method. To release a loc+) it must call its unloc+/ method. Insteado" the implicit loc+ing and unloc+ing o" a synchronized bloc+ or method) a loc+ provides the"le(ibility o" manually calling loc+/ and unloc+/.

* $oc+ also has a try$oc+/ method. This try$oc+/ method returns a true or "alse value) true i" it managed to get the loc+) "alse otherwise. The program does not bloc+ i" try$oc+/ does notsucceed) in contrast to the loc+/ method) and the behavior o" a thread i" it tries to enter asynchronized bloc+ or method. In addition) a di""erent version o" try$oc+/ allows you tospeci"y the amount o" time the thread waits to establish a loc+ be"ore it returns true or "alse.

The "ollowing is our class 3y?rinter implementation in our 3yThread7 e(ample/ using loc+s.

!ote that there is no longer the implicit unloc+ing that happens at the end o" a synchronized

bloc+) so any loc+/ or try$oc+/ call must be "ollowed by an unloc+/ call.

i#port ava.util.concurrent.loc5s.7;

class My2rinter {

final >oc5 l = ne ?eentrant>oc5(); // ?eentrant>oc5 is an i#ple#entation

// of the >oc5 interface

public void print0(int value) {

boolean %ot>oc5 = false;

hile (@%ot>oc5) {

%ot>oc5 = l.try>oc5();

if (@%ot>oc5) {

"yste#.out.println(,Anable to %et loc5B try a%ain

next ti#e,);

try {

Thread.sleep((int)(Math.rando#() 7 000));

} catch (nterrupted1xception e) { }

}

}

for (int i = 0; i < 0; i!!) {

"yste#.out.print(value);

}

"yste#.out.println(,,); // neline after 0 nu#bers

l.unloc5();

}

}

%ur wait/ and noti"y/ methods can only be called on the intrinsic loc+ o" a synchronizedmethod or bloc+. To do the same with the $oc+ class) we can use its newCondition/ method)which returns an ob&ect o" type Condition. * condition ob&ect has an await/ method which isthe e;uivalent o" a wait/ call it waits on the $oc+ ob&ect the condition was e(tracted "rom/. Towa+e up a thread that is waiting on a loc+ ob&ect) all condition ob&ects have a signal/ method)which is the e;uivalent o" a noti"y/ call.

'or e(ample) this is an e(cerpt our Shared9ars class modi"ied using loc+s and conditions.

i#port ava.util.concurrent.loc5s.7;

class "hared8ars {

&inal 'oc l = ne Reentrant'oc();final ondition e#ptyondition = l.neondition();

// #ethod for insertin% a value

%perating Systems 4@

Page 15: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 15/17

J.E.D.I.

public void insert8alue(int value) {

l.loc() ## enae locif (top < array.len%th) {

array&top' = value;

top!!;

if (top == ){empty*ondition.noti&y();}

}

l.unloc();}

// #ethod for %ettin% a value

public int %et8alue() {

l.loc();if (top <= 0) {

try {

empty*ondition.ait();} catch (nterrupted1xception e) { }

}

top99;

l.unloc();return array&top';

}

}

There are other classes in the &ava.util.concurrent.loc+s pac+age. %ne o" them is the

-eentrant-eadrite$oc+ class) which has methods which return loc+s. These loc+s can be usedas a solution to the -eaders2riters problem.

 1.+.2 Executorshenever we create a thread) we manually state when that thread is e(ecuted. 'or instance)given the "ollowing thread=

class MyThread i#ple#ents ?unnable { ... }

e manually start the thread by the two commands=

Thread t = ne Thread(#t);

t.start();

*n implementing class o" the E(ecutor inter"ace abstracts thread starting "rom the

programmer. 'or instance) instead o" the above code) we have the "ollowing=MyThread #t = ne MyThread();

1xecutor e = ne Thread2ool1xecutor(0); // accepts #ax 0 threads

e.execute(#t);

e.execute(otherThreads);

%ur e(ample uses the Thread?oolE(ecutor class. This class runs our inputted threads via the

e(ecute/ method/ via a ready pool o" e(ecution threads. These e(ecution threads reduce theoverhead needed "or thread creation) a thread is merely passed as a parameter to an alreadyrunning wor+er thread "or e(ecution.

* parameter speci"ied in the constructor indicates how many threads the e(ecutor can run all

at once. I" an e(ecutor is not used) then threads are run at the moment they are started. I"

%perating Systems 40

Page 16: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 16/17

J.E.D.I.

there are too many threads that are running all at once) the system can not cope and allthreads are stopped. *n e(ecutor allows "or a speci"ied ma(imum number o" running threads)allowing the system to handle only the number o" threads it can control and re&ect or ;ueuethose it cannot.

*dditional methods indicate how incoming threads are to be ;ueued or to when to terminateinactive threads. * subclass o" Thread?oolE(ecutor) the ScheduledThread?oolE(ecutor class)has methods that allow "or a partciular thread to start at a certain time o" the day) or berepeated periodically.

1.+.3 /oncurrent /ollections

The &ava.util.concurrent pac+age includes collection classes that can be used with

multithreaded programs use without having to worry about synchronization problems. 'orinstance) the <loc+ingLueue class creates a "irst2in2"irst out ;ueue that automatically bloc+sthreads when they try to add to a "ull ;ueue or retrieve values "rom an empty one. E(ecutionautomatically resumes when another thread removes a value "rom a "ull ;ueue or adds data toan empty one.

1.+.4 0tomic ariables

*s we have seen in our ?roducer2Consumer problem) the commands=

arrayMtopN B new valueO,

top,

must be e(ecuted without any interleaving. This is called atomic e(ecution) each commandmust be e(ecuted as a single whole.

#owever) even single commands are not atomic. Consider the command=

top ,

Top is divided into three parts when run on the C?5

4. Pet the value o" top

7. *dd 4 to that value

8. Save that value to the address o" top.

*ll these three commands must be e(ecuted without any interleaving commands "rom otherthreads. %ne way around this is to have a synchronized increment method.

class Shared9ars A

int top,

public synchronized inctop/ A

top,

3ost o" the other arithmetic operations are sadly) non2atomic as well) meaning each

mathematical operation) when dealing with shared variables) has to be in a synchronized bloc+to be sa"e. This includes even assignment statements. To avoid this tediousness) the

 &ava.util.concurrent.atomic pac+age provides already thread2sa"e classes.

'or instance) the *tomicInteger class provides some o" the methods below=

%perating Systems 4G

Page 17: Teacher's Notes - Lab Chapter 5 - Java Threads

7/25/2019 Teacher's Notes - Lab Chapter 5 - Java Threads

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-5-java-threads 17/17

J.E.D.I.

● void increment*ndPet/ 2 per"orms an increment operation atomically

● void add*ndPetint delta/ Q adds delta to the *tomicInteger atomically.

There are also implementations li+e this "or an integer array or an ob&ect re"erence variable.

*lso) most o" the classes in &ava.util are already thread sa"e.

%perating Systems 4H