CS242 Advanced Programming Concepts in Java - PowerPoint PPT Presentation

1 / 34
About This Presentation
Title:

CS242 Advanced Programming Concepts in Java

Description:

Intro to Multithreading: java.lang.thread. Read Java Tutorial. http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html ... – PowerPoint PPT presentation

Number of Views:20
Avg rating:3.0/5.0
Slides: 35
Provided by: janicets
Category:

less

Transcript and Presenter's Notes

Title: CS242 Advanced Programming Concepts in Java


1
CS242Advanced Programming Concepts in Java
  • 11/27/07
  • Multithreading

Prof. Searleman jets_at_clarkson.edu
2
Outline
  • Review of Maps
  • Recognizing Design Patterns
  • Intro to Multithreading java.lang.thread
  • Read Java Tutorial
  • http//java.sun.com/docs/books/tutorial/essential/
    concurrency/index.html
  • HW6 posted
  • Exam2 Tonight, Nov 27, 700 pm, SC 362

3
Map interface
  • object that maps keys to values
  • cannot contain duplicate keys
  • each distinct key maps to exactly one value
  • different keys may map to the same value
  • essentially a group of ltkey,valuegt pairs
  • methods
  • put(Object key, Object value)
  • get(Object key) returns the value with that
    key
  • containsKey()
  • containsValue()

4
Map interfaces implementations
5
Example map integer code to major
6
/ key is an Integer, value is a String / Map
majors new HashMap() Integer code13 new
Integer(13) Integer code36 new
Integer(36) Integer code38 new
Integer(38) Integer code24 new
Integer(24) majors.put(code13, Electrical
Eng) majors.put(code36, Computer
Science) majors.put(code38, Digital Arts
Sciences) majors.put(code24, Marketing) Integ
er key code13 System.out.println(
majors.get(key) )
7
/ Parameterized key is an Integer, value is
a String / MapltInteger,Stringgt majors new
HashMapltInteger,Stringgt () majors.put(code13,
Electrical Eng) majors.put(code36, Computer
Science) majors.put(code38, Digital Arts
Sciences) majors.put(code24, Marketing) Integ
er key code13 System.out.println(
majors.get(key) )
8
Collection-view for Map
  • keySet() returns Set of keys in the map
  • values() returns Collection of values in the map
  • entrySet() returns Set of key-value pairs each
    pair has type Map.Entry

9
MapltInteger,Stringgt majors new
HashMapltInteger,Stringgt () majors.put(code13,
Electrical Eng) majors.put(code36, Computer
Science) majors.put(code38, Digital Arts
Sciences) majors.put(code24, Marketing) /
and so on / Set keys majors.keySet() for
(Iterator it keys.iterator() it.hasNext() )
System.out.println( it.next() )
10
MapltInteger,Stringgt majors new
HashMapltInteger,Stringgt () majors.put(code13,
Electrical Eng) majors.put(code36, Computer
Science) majors.put(code38, Digital Arts
Sciences) majors.put(code24, Marketing) /
and so on / Collection values majors.values()
for (Iterator it values.iterator()
it.hasNext() ) System.out.println( it.next()
)
11
MapltInteger,Stringgt majors new
HashMapltInteger,Stringgt () Set keys
majors.keySet() Collection values
majors.values() What about entrySet()? i.e.
majors.entrySet() returns what data
type? special datatype that works for all maps
Map.Entry
answer Set of Map.Entry
12
MapltInteger,Stringgt majors new
HashMapltInteger,Stringgt () majors.put(code13,
Electrical Eng) majors.put(code36, Computer
Science) majors.put(code38, Digital Arts
Sciences) majors.put(code24, Marketing) Set
pairs majors.entrySet() for (Iterator it
pairs.iterator() it.hasNext() ) Map.Entry
entry it.next() System.out.println(Key
entry.getKey() ) System.out.println(Value
entry.getValue() )
13
Paradigm to iterate over key-value tuples for an
arbitrary map m for (Iterator i
m.entrySet().iterator() i.hasNext() )
Map.Entry e (Map.Entry) i.next() // the
following prints out the keyvalue tuple
System.out.println(e.getKey() " "
e.getValue())
14
public class University private static final
String name "Clarkson" private static
MapltString,ListltStudentgtgt enrollment new
HashMapltString,ListltStudentgtgt() public static
void main(String args) / initialize
the 3 map entries / enrollment.put("AS", new
ArrayList()) enrollment.put("Bus", new
ArrayList()) enrollment.put("Eng", new
ArrayList())
15
try Scanner inscan new Scanner( new
FileReader("school.dat")) inscan.useDelimiter("
\\") String name int major Date year
ListltStudentgt undergraduates String key

16
while(inscan.hasNext()) key
inscan.next() name inscan.next() major
inscan.nextInt() year new
Date(inscan.next()) inscan.nextLine()
Student st new Student(name, major, year)
undergraduates (ListltStudentgt)enrollment
.get(key) undergraduates.add(st)
enrollment.put(key, undergraduates ) // can
simplify the above how?
17
/ Version1 prints each key and the list of
students / System.out.println("Version 1") for
(Iterator i enrollment.entrySet().iterator()
i.hasNext() ) Map.Entry e
(Map.Entry) i.next() System.out.println(e.getKe
y() " " e.getValue() )
18
/ Version2 prints each key and then
iterates over list of students / System.out.print
ln("Version 2") for (Iterator it
enrollment.entrySet().iterator()
it.hasNext() ) Map.Entry e (Map.Entry)
it.next() System.out.println(e.getKey()
"\n") for (Iterator trav ((List)
e.getValue()).iterator()
trav.hasNext() ) System.out.println("\t"
trav.next())
19
Recognizing Design Patterns
Model-View-Controller Architectural Pattern
Observer Design Pattern
Diagram of the relationship between the Model,
View, and Controller. Note the solid lines
indicate a direct association, and the dashed
lines indicate an indirect association (e.g.,
observer pattern). (from Wikipedia)
20
Multithreading
  • What is a thread?
  • process running program
  • thread single, sequential flow of control
    within a program

21
One thread of execution
22
Multithreaded execution
  • thread lightweight process
  • the threads share the resources data in the
    program
  • each thread has its own stack and program counter

23
Example bouncing balls
  • Consider a GUI with two buttons when you click
    on start, it activates a ball that will be
    repeatedly drawn in the GUI (simulating a
    bouncing ball or atom), and when you click on
    close the application terminates.

24
public class Ball // non-threaded version //
constructor draw() move() etc. public void
bounce() draw() for (int i 1 i
lt 1000 i) move() try
Thread.sleep(5) catch(InterruptedExcep
tion e)
25
// non-threaded application addButton(p,
"Start", new ActionListener() public
void actionPerformed(ActionEvent evt)
Ball b new Ball(canvas)
b.bounce() )
26
Thread.sleep() is a static method in the Thread
class that puts a thread to sleep (i.e. pause)
for a given number of milliseconds problem
while the first ball is bouncing, the others
cant start also, cant close the window, so the
GUI is non-responsive solution make the program
more responsive by running the code that moves
the ball in a separate thread
27
Runnable interface
  • There are two basic methods, and both require the
    Runnable interface, whose only method is
  • public void run()
  • When an object implementing interface Runnable is
    used to create a thread, starting the thread
    causes the object's run method to be called in
    that separately executing thread. The general
    contract of the method run is that it may take
    any action whatsoever.

28
Implementing a thread
  • method 1 extend the Thread class place code in
    the run() method
  • method 2 implement the Runnable interface
  • variant of method 2 use an inner class to
    provide a Runnable implementation
  • Method 2 is recommended

29
Method 1 extend Thread
public class Ball extends Thread //
constructor draw() move() etc. public void
run() try draw() for
(int i 1 i lt 1000 i)
move() Thread.sleep(5)
catch(InterruptedException e)
Not a good use of inheritance a ball is a
thread???
30
How to create a thread
  • Ball b new Ball() // wont run
  • To create a new, runnable thread, call start()
  • b.start()
  • NOTE NEVER call run() directly
  • start() creates the thread, sets up the context,
    and calls run()

31
// multithreaded version addButton(p, "Start",
new ActionListener() public void
actionPerformed(ActionEvent evt)
Ball b new Ball(canvas)
b.start() )
32
java.lang.Thread
  • Thread() constructor must start the thread to
    activate its run method
  • void run() override this method customize the
    code to be executed in a separate thread
  • void start() starts the new thread this method
    returns immediately the new thread runs
    concurrently with others
  • static void sleep(long ms) puts the currently
    executing thread to sleep for the given time

33
Thread states
  • new
  • runnable
  • blocked
  • dead
  • e.g.
  • Ball b new Ball() b is in the new state
    (not yet runnable)
  • b.start() // puts b in the runnable state
    (not necessarily running yet)

34
Life Cycle of a Thread
Write a Comment
User Comments (0)
About PowerShow.com