Docsity

Java Threading: Creating and Running Threads, Synchronization, and Sharing Data - Prof. Kr, Study notes of Linguistics

Toggle sidebar
bg1
Concurrent Programming
l Thd
cs480 (Prasad) L11Threads 1
c
l
ass
Th
rea
d
interface Runnable
class Object
• Multiprocessing
– Using Multiple Processors.
• Multiprogramming (Batch)
– Switch and execute different jobs simultaneously,
to improve CPU utilization.
• Multitasking (Interactive)
– Perform more than one task at a time for each user,
granularity
cs480 (Prasad) L11Threads 2
to improve response time.
•Multithreading
– Threads in a user task (process) can share code, data,
and system resources, and access them concurrently.
– Each thread has a separate program counter,
registers, and a run-time stack.
Multitasking
!ls
!more a.txt
!emacs -nw a.java
!
ls
xclock &
netscape &
cs480 (Prasad) L11Threads 3
!
gcc a.c ;
a.out
!…
!logout
emacs a.java &
javac a.java ;
java a
...
Browser : A Multithreaded Application
• Concurrent Activities:
– Scrolling a page.
– Downloading an applet/image over the internet.
– Playing animation and sound simultaneously.
cs480 (Prasad) L11Threads 4
–
Printing a page in the background.
– Updating Stock Quotes automatically.
– FTP-ing a remote file.
–...
•Browser is a mini-OS!
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Java Threading: Creating and Running Threads, Synchronization, and Sharing Data - Prof. Kr and more Study notes Linguistics in PDF only on Docsity!

Concurrent Programming

l Th d

cs480 (Prasad) L11Threads 1

class Thread

interface Runnable

class Object

• Multiprocessing

– Using Multiple Processors.

• Multiprogramming (Batch)

– Switch and execute different jobs simultaneously,

to improve CPU utilization.

• Multitasking (Interactive)

– Perform more than one task at a time for each user,

granularity

cs480 (Prasad) L11Threads 2

to improve response time.

• Multithreading

– Threads in a user task (process) can share code, data,

and system resources, and access them concurrently.

– Each thread has a separate program counter,

registers, and a run-time stack.

Multitasking

!ls

!more a.txt

!emacs -nw a.java

 ls

 xclock &

 netscape &

!gcc a.c ;

a.out

!logout

 emacs a.java &

 javac a.java ;

java a

Browser : A Multithreaded Application

• Concurrent Activities:

– Scrolling a page.

– Downloading an applet/image over the internet.

– Playing animation and sound simultaneously.

– Printing a page in the background.

– Updating Stock Quotes automatically.

– FTP-ing a remote file.

• Browser is a mini-OS!

Threads in Java

• A single sequential flow of control

(of execution of expressions and

statements) is called a thread.

• A thread independently executes Java

cs480 (Prasad) L11Threads 5

p y

code, but may share address space

with other threads. (cf. Process)

Java primitives for concurrent programming

are based on Hoare’s monitors.

Motivation

Application independent interleaving of threads.

• Support Concurrent Activities

  • Multimedia Applications
  • Advertisements, Sports/stocks ticker

cs480 (Prasad) L11Threads 6

• Improve user response

  • User input in interactive programs
  • I/O in networked programs “in the background”

• Improve CPU utilization

  • Demand-driven thread-scheduling

Overall Gameplan

• How to create and execute multiple threads?

  • Interleaved computations
  • Indiscriminate interleaving interferes with

application semantics

• Introduce Mutual Exclusion constucts

  • Example : Printing documents on a shared printer

• Introduce Synchronization constructs

  • Example : Buffering on a shared printer

Java Primitives

• Mutual exclusion

  • synchronized methods in a class cannot be run

concurrently on behalf of different threads.

  • synchronized statement locks an object.
    • “Object” is an instance of a class
    • “Object” is an instance of a class

( incl. class Class).

• Synchronization / Cooperation

  • Methods wait(), notify(), notifyAll() etc.

in class Object enable threads to communicate

and regulate each other’s progress.

Alternative :Creating and Running

Threads

  • Threads can also be created from an

instance of a class implementing the

cs480 (Prasad) L11Threads 13

interface Runnable.

  • Required when the class is defined by

extension.

Example using interface Runnable

class Echo implements Runnable { int id; Echo(int i) { id = i; } public void run() { while (true) { System.out.println(id +“ ABC ”); // yield();

cs480 (Prasad) L11Threads 14

// yield(); } } public static void main (String[] args) { new Thread (new Echo(1)). start(); new Thread (new Echo(2)). start(); } }

Same Example in C#

using System.Threading;

class Echo { int id; Echo(int i) { id = i; } public void run() { while (true) while (true) System.Console.WriteLine(id + " ABC "); } public static void Main () { new Thread ( new ThreadStart (new Echo(1).run)). Start(); new Thread ( new ThreadStart (new Echo(2).run)). Start(); } }

Alternate Rendition in Java

class Echo implements Runnable { public void run() { try {{ while (true) { Thread.sleep(1000); System.out.println(“ABC”); } }} catch (InterruptedException e) { }} catch (InterruptedException e) { return; } } public static void main (String[] args) { Runnable r = new Echo(); new Thread(r). start(); } }

Threads and Applets

cs480 (Prasad) L11Threads 17

A Simple Bouncing Ball Animation

class Ball {

static final int TOP = 10, BOTTOM = 150;

int incr = 2;

int ypos = TOP;

void paint(java.awt.Graphics g) {

if (ypos < TOP || ypos > BOTTOM)

cs480 (Prasad) L11Threads 18

(yp || yp )

incr= -incr;

ypos += incr;

g.setColor(java.awt.Color.cyan);

g.fillOval(10,ypos, 10,10);

//

public class Bounce extends java.applet.Applet {

Ball b;

public void init() {

b = new Ball();

setBackground(java.awt.Color.red);

public void paint(java awt Graphics g) {

public void paint(java.awt.Graphics g) {

b.paint(g);

repaint(15);

/* try { while (true) {

Thread.sleep(15); repaint(); } } catch (InterruptedException e) {}; */

Threaded Applet

public class ThreadedBounce

extends java.applet.Applet

implements Runnable {

Ball b;

Thread t;

public void init() {

public void init() {

b = new Ball();

setBackground(java.awt.Color.red);

t = new Thread(this);

t.start();

...

public void run() {

try {

while (true) {

sleep(600);

c = new java.awt.Color(

(float) Math random()

cs480 (Prasad) L11Threads 25

(float) Math.random(),

(float) Math.random(),

(float) Math.random() );

} catch (InterruptedException e) {};

Mutual Exclusion

cs480 (Prasad) L11Threads 26

Sharing Data

Threads Sharing Data

class Shared { private int cnt = 0; // synchronized void print(String Id) { System.out.print(Id + “:” + cnt ); System.out.println( “-” + ++cnt); } } } class Shared { private int cnt = 0; void print(String Id) { synchronized (this) { System.out.print(Id + “:” + cnt ); System.out.println( “-” + ++cnt); } } }

class SharingThread extends Thread {

private static Shared s = new Shared();

String Id;

SharingThread (String Name) {

Id = Name;

start();

public void run () {

while (true) {

while (true) {

s.print(Id); // yield();

public static void main (String [] args) {

new SharingThread(“A”) ;

new SharingThread(“B”) ;

Motivation for Mutual Exclusion

Concurrent AccessConcurrent Access Mutual Exclusion with yield()

A:368-

A:369-

B:370-

A:370-

A:372-

A:373-

A:374-

A:828-

B:829-

B:830-

A:831-

B:832-

A:833-

A:693-

A:694-

A:695-

B:696-

B:697-

B:698-

cs480 (Prasad) L11Threads 29

A:374 375

B:371-

B:376-

B:377-

B:378-

B:379A:375-

A:381-

A:382-

A:383-

A:833- 834

B:834-

A:835-

B:836-

B:837-

A:838-

B:839-

B:699-

B:700-

B:701-

A:702-

A:703-

A:704-

A:705-

// C# Equivalent using System; using System.Threading; class Shared { private int cnt = 0; public void print(String Id) { lock (this) { Console.Write(Id + ":" + cnt); Console.WriteLine("-" + ++cnt); }; } } class SharingThread { private static Shared s = new Shared(); S i Id

cs480 (Prasad) L11Threads 30

String Id; SharingThread (String Name) { Id = Name; } public void run () { while (true) { s.print(Id); } } public static void Main (string [] args) { new Thread (new ThreadStart (new SharingThread("A").run) ). Start() ; new Thread (new ThreadStart (new SharingThread("B").run) ). Start() ; } }

Interaction of Language Features

run() method case study

Subclassing : Access Control

class Thread { ... public void run() { } } class SubThread extends Thread { public void run() { ... }

Thread t = new SubThread();

t. run()

/****************** ILLEGAL ********************

void run() { ... }

******************* ILLEGAL ********************

  • Otherwise, run() can be invoked on a SubThread

instance via (its reference in) a Thread variable

(due to dynamic binding) in another package.

Thread Scheduling

cs480 (Prasad) L11Threads 37

Blocked Thread

  • A thread is blocked (that is, it is not runnable) if it is:
    • sleeping.
    • suspended.
    • waiting.

cs480 (Prasad) L11Threads 38

waiting.

  • executing a “blocked” method.
  • “blocked” for I/O.
  • Java neither detects nor prevents deadlocks.

Thread Scheduling

  • Java runs a non-blocked ( runnable )

highest-priority thread.

  • A thread can be preempted by a higher

priority thread that becomes runnable. p y

  • The scheduler may however choose to run

lower priority thread, to avoid starvation.

  • The same (highest) priority threads are

run in round-robin fashion.

Scheduling Ambiguity

  • JVM on Windows uses time-slicing to

schedule same priority threads.

(“Fair policy”)

  • JVM on Solaris chooses one of the JVM on Solaris chooses one of the

same priority threads to run until the thread

voluntarily relinquishes the CPU (by

sleeping, yielding, or exiting), or

until a higher priority thread preempts it.

Cooperative Concurrent Threads

Producer-Consumer Problem

cs480 (Prasad) L11Threads 41

Producer-Consumer Problem

Bounded-Buffer Problem

(Clients and Servers : Resource Sharing)

Simplistic 1-Cell Buffer

class Buffer {

Object x;

// synchronized

public void put (Object _x, String id) {

System.out.println(

"Done << " + id + " puts " + _x);

x = _x;

cs480 (Prasad) L11Threads 42

// synchronized

public Object get (String id) {

System.out.println(

"Done >> " + id + " gets " + x);

return x;

class Producer extends Thread { private Random r = new Random(); Buffer b; String id; public Producer(Buffer _b, String _id) { b = _b; id = _id; } public void run () { int delay; Integer ir; try { while (true) { while (true) { delay = Math.abs(r.nextInt() % 1999) + 50; sleep(delay); ir = new Integer(delay); System.out.println("Ready << "+id+" puts "+ ir);

b.put(ir, id);

}catch (Exception e){System.out.println("Exception$ " + e);}; } }

class Consumer extends Thread { private Random r = new Random(); Buffer b; String id; public Consumer(Buffer _b, String _id) { b = _b; id = _id; } public void run () { int delay; Integer ir = null; try { while (true) { delay = Math.abs(r.nextInt() % 1999) + 50; sleep(delay); System.out.println("Ready >> " + id + " gets ");

ir = (Integer) b.get(id);

} catch (Exception e) {System.out.println("Exception$ " + e);}; } }

public synchronized Object

get (String id) throws Exception {

while (empty) wait();

empty =! empty;

System.out.println("Done >> "+id+" gets "+x);

notifyAll();

return x;

cs480 (Prasad) L11Threads 49

return x;

  • Note that notify cannot always be used in place of

notifyAll because a consumer may be woken up.

  • while required because notifyAll due to a producer

does not guarantee that wait-ing consumers will find an

item in the buffer.

Synchonization and Mutual Exclusion

Ready >> C2 gets Ready >> C1 gets Ready << P1 puts 1672 Done << P1 puts 1672 Done >> C2 gets 1672 Ready << P2 puts 774 Done << P2 puts 774 Done >> C1 gets 774

Ready << P1 puts 622 Done << P1 puts 622 Ready >> C1 gets Done >> C1 gets 622 Ready >> C2 gets Ready << P2 puts 1447 D P2 t 1447

cs480 (Prasad) L11Threads 50

Done >> C1 gets 774 Ready << P1 puts 168 Done << P1 puts 168 Ready >> C1 gets Done >> C1 gets 168 Ready << P2 puts 1263 Done << P2 puts 1263 Ready >> C1 gets Done >> C1 gets 1263 …

Done << P2 puts 1447 Done >> C2 gets 1447 Ready << P2 puts 96 Done << P2 puts 96 Ready << P2 puts 95 Ready >> C1 gets Done >> C1 gets 96 Done << P2 puts 95 ...

Methods in class Object

  • public final void wait() throws

InterruptedException {...}

  • Current thread is suspended (after atomically

releasing the lock on this) until some other thread

invokes notify() or notifyAll() or interrupts.

  • public final void notify() {...}
    • Notifies exactly one thread waiting on this object for

a condition to change. The awakened thread cannot

proceed until this thread relinquishes the lock.

  • public final void notifyAll() {...}
    • These methods must be invoked inside synchronized

code or else IllegalMonitorStateException will be thrown.

Single Cell Buffer in C#

using System; using System.Threading; class Buffer { Object x; bool empty = true; public void put (Object _x, string id) { lock(this){ while (!empty) Monitor.Wait(this); empty =! empty; Console.WriteLine("Done << " + id + " puts " + _x); x = _x; Monitor.PulseAll(this); } } public Object get (string id) { lock(this){ while (empty) Monitor.Wait(this); empty =! empty; Console.WriteLine("Done >> " + id + " gets " + x); Monitor.PulseAll(this); return x; } } }

class Producer { private System.Random r = new System.Random(); Buffer b; String id; public Producer(Buffer _b, String _id) { b = _b; id = _id; } public void run () { int delay; try {

cs480 (Prasad) L11Threads 53

while (true) { delay = r.Next(2000) + 50; Thread.Sleep(delay); Console.WriteLine("Ready << " + id + " puts " + delay); b.put(delay, id); } } catch (Exception e){Console.WriteLine("Exception$ " + e);}; } }

class Consumer { private System.Random r = new System.Random(); Buffer b; String id; public Consumer(Buffer _b, String _id) { b = _b; id = _id; } public void run () { int delay; try {

cs480 (Prasad) L11Threads 54

while (true) { delay = r.Next(2000) + 50; Thread.Sleep(delay); Console.WriteLine("Ready >> " + id + " gets "); delay = (int) b.get(id); } } catch (Exception e) {Console.WriteLine("Exception$ " + e);}; } }

public class PCB {

public static void Main(string[] args) {

Buffer b = new Buffer();

new Thread( new ThreadStart(new Consumer(b,"C1").run)). Start();

new Thread( new ThreadStart(new Producer(b,"P1").run)). Start();

try {Thread.Sleep(1000);}

cs480 (Prasad) L11Threads 55

y p catch (Exception e){Console.WriteLine("Exception$ " + e);};

new Thread( new ThreadStart(new Consumer(b,"C2").run)). Start();

new Thread( new ThreadStart(new Producer(b,"P2").run)). Start();

}

}