60 likes | 133 Views
Threads, pt 2. Assignment 7 Example. COMP 401 Spring 2014 Lecture 21 4/10/2014. sleep() and timing execution. Thread.sleep ( int ms ) Sleeps for ms milliseconds Accuracy not guaranteed System.nanoTime () Highest resolution timer available in Java Return value is long
E N D
Threads, pt 2.Assignment 7 Example COMP 401 Spring 2014 Lecture 21 4/10/2014
sleep() and timing execution • Thread.sleep(intms) • Sleeps for ms milliseconds • Accuracy not guaranteed • System.nanoTime() • Highest resolution timer available in Java • Return value is long • Difference in value between two different calls represents duration in nanoseconds. • Actual resolution is courser than a nanosecond. • lec22.v1
Demonstrating Parallelism • lec22.v2 • Generating 100 million random numbers • With varying number of threads from 1-16 • Why decrease in performance between 1 and 2? • How many cores does my machine have?
Swing and multithreading • Swing is NOT multithreaded • After being set up, the only thread that can safely interact with Swing components is the Swing event thread. • lec22.v3 • Skeleton for timer application • lec22.v4 • Badly written timer application • Creates a background thread that is supposed to periodically update user interface. • Seems to work OK • But may not always work.
SwingUtilities.invokeLater() • Static helper method for properly asking Swing event thread to do something. • Takes a Runnable object as parameter • Does not create a new thread. • Schedules execution with existing Swing event thread. • lec25.v5
Anonymous Classes • WidgetUpdater is kind of ugly. • Instances are generated just to run once • Anonymous classes provide a way to define and create an object instance that implements an interface without having to formally define a class. • Special syntax evaluates as an expression • Resulting instance can not have a constructor or any encapsulated state. • Just implementation of interface • But does have access to any local variables declared as finalas well as any encapsulated state of the current object when used. • lec22.v6