Docsity

Lecture Slides on Threads 1 - Intermediate Programming | CS 251L, Assignments of Computer Science

Partial preview of the text

Download Lecture Slides on Threads 1 - Intermediate Programming | CS 251L and more Assignments Computer Science in PDF only on Docsity!

CS251 Intermediate Programming

Lecture 25

Threads

  • Final Monday, December 15.• Homework 6 due next Wednesday.• Last Quiz next Monday.

A thread is a sequential

(^) fl ow of control within a program.

stepthe results of previous steps, and so must begin after the priorDependencies in algorithms (where computational steps rely oncompletion before the following step can begin.computation, conditional test, function call) must run toEach step in a thread (assignment, arithmetic/logical (^) fi nishes) are often implicit in the sequence of steps in a

putprogrammer had to choose (maybe arbitrarily) which one todependency exists: the steps may be independent, and theJust because one program step follows another doesn’t mean asatisfy all the dependencies in an algorithm.program. Programmers learn to order program steps so as to (^) fi rst.

parallelism.multiple steps executing simultaneously. This is called In many cases, the algorithm would work correctly with

program.independently of and in parallel with the other threads in theEach of these “sub-programs” or threads executes(multithreading).individual programs can have multiple threads of controlThe multitasking concept has been extended such that arguments, etc.its independent Program Counter, local variables, methodEach thread has its own private call stack to keep track ofWithin each thread, steps are still processed sequentially.

shared by all threads in a program. Classes, objects, member variables, and static variables are

You can create new threads by either

  1. subclassing

(^) java.lanl.Thread

, instantiating it, and

calling its

(^) start()

(^) method.

  1. implementing the

(^) java.lang.Runnable

(^) interface in a

class, then instantiating a

(^) Thread

(^) with the

(^) Runnable

(^) as

an argument, and calling

(^) start()

(^) on the

(^) Thread

Thread

(^) and (^) Runnable

(^) both de

fine a

(^) run()

(^) method which

Thegets called when the new thread starts. (^) start()

(^) method of

(^) Thread

(^) returns immediately, so the

method that called

(^) start()

(^) will be running in parallel with

the (^) run()

(^) method of the new thread.

create or have running at any time.There are no hard limits to the number of threads you may Practical limits depend on the computing platform.

{ public class Counter implements Runnable { public void run()/ This is the only method declared by the java.lang.Runnable interface./** for (int i = 0; i < 100; i++) System.out.println(i);**

} { public class SomeOtherClass} { public static void main(String[] args) t.start(); // interface method Runnable.run() will be called when Thread startsThread t = new Thread(c); // Thread constructor can take a Runnable argumentCounter c = new Counter(); } }

Threads are useful because: the form of more processing units instead of faster units.Increases in computing performance now come mostly in etc.)maintained in the CPU (program counter, local variables,because of the “state” information that needs to beA single thread can only run on one CPU at a time

largeactions while running a long computation, manipulating aA multithreaded program can continue responding to user

(^) fi le, communicating with a printer, etc.

single-threaded environment are kept active.USB I/O, graphics, etc.). Resources that would be idle in acan continue using other, available resources (net work I/O, If a thread gets stuck waiting for disk I/O, other threads

structure, which was in a momentarily inconsistent state).program wasn’t in the middle of changing some important dataoperating system when it was “safe” to switch tasks (i.e., theIn the early days of multitasking, programs would tell theown CPU. There is no loss of responsiveness.thread, the illusion is maintained of each thread having itseach for a small “slice” of time before rotating to the nextIf the CPU(s) rotate quickly through the threads, working onthreads have to share each CPU.If there are more active threads than CPUs/cores, multiple frozen until it “yielded” the CPU. If a program failed to do this, all other programs weredoing and transfer control to another program is tedious.Writing code to frequently “wrap up” what the program is

thread.actively modifying the data, potentially confusing the othercondition, where the OS task switches when one thread is Two threads accessing the same data can encounter a racePreemption can occur at any time, during any program step.interruption.other threads may have changed shared objects during theThe thread has no indication that it was interrupted, butin at preemption time.stack (including Program Counter) to the same condition it wasWhen a thread gets to execute again, the OS restores the callgive up the CPU, it transfers control automatically.yield control. When the OS determines it’s time for a thread toContemporary operating systems don’t rely on programs to

43 48 12 74

4 ArrayList l

size

array Thread 2

l.add(2, 91);

l.remove(3); // remove 74

To insert an element into an

(^) ArrayList

, it must copy the

element, and change theexisting elements for ward to make a space, insert the new

(^) size

fi

eld of the data structure.

Thread 1

43 48 12 12 74

4 ArrayList l

size

array

Thread 1

Thread 2

l.add(2, 91);

l.remove(3);

remove() Thread 2 starts running. It starts working on its Suppose Thread 1 is preempted here by the scheduled, and

operation. It thinks element

is at the end of

the list, so it does not copies, but it decrements the

(^) size

field and is

fi

nished.

43 48 91 12 74

4 ArrayList l

size

array

Thread 1

Thread 2

l.add(2, 91);

l.remove(3);

Now there is a problem with the

(^) ArrayList

. One of the

values is “lost” because the

(^) size

fi

eld says there are only

elements in the

fi

eld, but there should be

You mark a critical section using acalled critical sections.one thread at a time (because they modify shared data) areSections of code which cannot safely be executed by more thanof data to prevent simultaneous access by other threads.occurs, preemptive multitasking systems let you “lock” piecesTo make up for the lack of control when a thread switch

(^) synchronized

(^) block.

theYou can mark an entire method as a critical section by using (^) synchronized

(^) modi

fier.

When a thread reaches a

(^) synchronized

(^) block, it will acquire

When itenter the critical section.Once the current thread succeeds in getting the monitor, it willwill block until the monitor becomes available.If another object already has the monitor, the current threadthe monitor (a kind of lock mechanism) for the object.

(^) fi nishes the critical section, it will release the monitor

and give other threads a chance to acquire it.

We recently talked about unmodi

fiability wrappers, which can

also inaccess the same collection without corrupting it. These aresafe” view into a collection, so that multiple threads canThere are also synchronized wrappers, which give us a “thread-give us a read-only view into a collection.

(^) java.util.Collections

SortedMap m = Collections.synchronizedSortedMap(map);Map m = Collections.synchronizedMap(map);SortedSet s = Collections.synchronizedSortedSet(ss);Set s = Collections.synchronizedSet(set);List l = Collections.synchronizedList(list); Collection c = Collections.synchronizedCollection(coll);

consistency issues in multiple processor environments. Locking before read access is required because of cache-accessing or modifying it. Each method in the wrapper locks the collection before

recipient seldom coincide at the same method invocation.available to multi-threaded applications because the caller andmethod arguments and return values. This mechanism isn’tMethods in a single-threaded environment communicate by same execution point so they are ready to exchange data.A mechanism is needed which brings multiple threads to the

wait()

(^) and (^) notify()

(^) are methods on

(^) java.lang.Object

Callingdo this. (so they are inherited by every object) that provide a means to

(^) wait()

(^) causes the current

(^) Thread

(^) to stop executing

until another Thread calls

(^) notify()

(^) on the same

(^) Object

wait()

(^) and (^) notify()

(^) can only be called from inside a

synchronized

(^) block whose target is the same object as the

object whose

(^) wait()

(^) or (^) notify()

(^) method is being called.

If you are calling

(^) x.wait()

, you have to be inside a

synchronized(x)

(^) block.