Presentation is loading. Please wait.

Presentation is loading. Please wait.

Advanced Java Class Threads.

Similar presentations


Presentation on theme: "Advanced Java Class Threads."— Presentation transcript:

1 Advanced Java Class Threads

2

3 Why Use Multiple Threads
User input thread & data-processing thread user-input has high priority but users are slow (compared to CPUs) so keep processing while waiting One thread per user Model independent objects in simulations Like traffic in Frogger !!!

4 Thread API & Features Thread class Runnable interface
Timer & TimerTask classes ThreadLocal class synchronized keyword wait(), notify(), notifyAll() (methods inherited from Object class) ThreadGroup class

5 Multi-threaded Processing
JVM schedules processor time for each thread and dictates when they get control You can not know or control exactly how this happens, and it will be different on different systems Different threads might “share” objects, so you don’t know which thread will access it first. You can schedule priorities for threads.

6 Making Your Own Threads
You have 2 options: extend Thread Fine if you’re not trying to extend anything else You get your thread directly by instantiating your class implement Runnable interface More flexible, therefore usually preferred. Your class can be a part of a class hierarchy unrelated to threads. You get your thread by passing an instantiation of your Runnable class to the thread constructor Either way, you deal with a Thread object.

7 Extending the Thread class
you must override run()with the code that this thread should execute when running Instantiate your class Don’t call run()!!! Call start() to begin execution.

8 Implementing Runnable Interface
Do this when you want to extend some other class. You must implement the run() method Create a new instance of the Runnable Pass it to the thread constructor. new Thread( myRunnable ) Call start (and other methods) on the thread, as before.

9 Thread Methods Static currentThread() Accessors
getPriority() & setPriority(int) isDaemon() & setDaemon(boolean) isAlive() Thread Control start() [which calls run()] sleep() yield() join() Once a Thread has finished execution, is it dead and may not be restarted. hi

10 Thread State Diagram improved version of figure 5-2, page 333

11 Deprecated Thread methods
You should not use stop(), suspend(), and resume() to control threads ! Reason: inherently unsafe: may leave data in an inconstant state. Deprecated since 1.2, which was when they figured this out. Instead, use flags (see next slide) ...

12 Alternatives to Deprecated Thread Methods
Give your Runnable class volatile boolean fields, possibly named ‘suspendFlag’ & ‘stopFlag’ Provide setters for them, possibly named ‘setSuspend(boolean)’ and ‘stopThread()’ Have your code check them frequently when stopFlag is true, end the run method, leaving the data in a consistent state when suspendFlag is true, have the Thread sleep a little bit, and then check the flag again.

13 Special Kinds of Threads
Daemon Threads continuous loop running in background listens for and handles requests when your program has only daemon threads left running, they are terminated and the application closes, because daemon threads normally never terminate on their own. TimerTask Threads you can schedule tasks to be done later run in background threads controlled by Timer objects use only for short tasks

14 Using TimerTasks Basics: Additional TimerTask methods:
extend TimerTask implement run() method instantiate your TimerTask subclass instantiate Timer schedule your TimerTask with the Timer Additional TimerTask methods: long scheduledExecutionTime() void cancel()

15 How to schedule a TimerTask in a Timer
Schedule an event to happen at a certain time, or after a certian delay: myTimer.schedule( myTask, time ) myTimer.schedule( myTask, delay ) Optionally, add a period parameter for recurring events. The period specifies the time between repeat occurances myTimer.schedule( myTask, time, period ) myTimer.schedule( myTask, delay, period) For tasks where the absolute timing of recurring events is important, like a clock striking on the hour, use these methods instead. If event is a little late, the others will ‘catch up’. myTimer.scheduleAtFixedRate(myTask, time, period ) myTimer.scheduleAtFixedRate(myTask, delay, period)

16 Good Multi-threading Techniques
If a variable should only be accessed by one thread, make it “Thread-safe”. If variables could be accessed by more than one thread, do one of the following: synchronize the code that calls them declare them volatile Think about how your threads could interfere with each other – try to avoid deadlock!

17 Thread-Safety Local variables are automatically thread-safe
Instance variables of an object whose methods are run by multiple threads are not safe declare methods that access it synchronized or declare the variable volatile Class (a.k.a. static) variables are not thread-safe or make them of type ThreadLocal or InheritableThreadLocal

18 Using ThreadLocal and InheritableThreadLocal
Good for when you want the field to be shared by multiple instances of the same class that are running in the same Thread, but not shared with instances of the class that are running on other Threads InheritableThreadLocal allows child Threads to share the variable with parent Threads. Methods: Object get() Object initialValue() void set( Object value)

19 Synchronization of methods
Why: to keep your variables in a consistent state How: declare the methods that access them to be synchronized What: JVM requires that no thread can access a method that another thread is currently in: provides a “lock” on the object (if instance method) or class (if static method)

20 Synchronization of code blocks
syntax: synchronized ( object_to_be_locked ) [fill in statement or code block] when to use: If a method is long, and many threads request it, synchronizing the smallest block of code that keeps the variables consistent will reduce the chance of deadlock.

21 Synchronization and Inner Classes
An inner class object has access to fields of the outer class object. These outer class instance variables may need to be protected in multithreaded programs. simply synchronizing the methods may not protect the outer class fields, the inner methods will be locked with the inner class instance and the outer methods will be locked with the outer class instance Therefore, an outer class method and an inner class method might run in parallel in different threads, causing inconsistent field values. Solution: instead of synchronizing the inner class method, synchronize the code with the enclosing object as a lock (see previous slide for syntax)

22 Communicating with wait() and notify()
methods inherited from Object that affect Threads: wait() wait(long timeout) wait(long timeout, int timeoutAddNanos) notify() notifyAll() Any object can call these, but only when the current Thread has a lock on the object. These methods are final -- they may not be overridden.

23 The wait methods [Inherited from Object]
Tells the current thread to release it’s lock, chill, and let another Thread (chosen by the JVM) execute wait() – waits until notified by another thread wait( long timeout ) – waits for the specified number of milliseconds wait( long timeout, int timeoutAddNanos) – waits for the specified number of milliseconds + the specified number of nanoseconds

24 The notify methods [Inherited from Object]
notify() - the JVM chooses one thread that has been waiting, and puts it into a runnable state. As soon as it can aquire the needed lock, it starts. notifyAll() – the JVM places all waiting threads into a runnable state, and then chooses one to get control and execute. The others are poised, ready to go as soon as they can get the necessary lock.

25 When to use wait and notify
When a Thread needs to wait until a particular condition is satisfied before continuing. Alternative to sleep() Typical usage: while (condition) { wait(); } (Check the condition again when notified in case the notification was unrelated to your condition) Use notify() when efficiency is a special concern, and all waiting threads are waiting for the same Object lock, so that any Thread the JVM chooses would be appropriate. Use notifyAll() when Threads are waiting for different Object locks. Each thread will check it’s condition, and at least one Thread should become able to continue.

26 Thread Grouping Why: What:
you can protect one group of threads from another you can perform operations [setPriority or interrupt) on all the threads in the group at once, instead of having to iterate through What: stores a collection of Threads that have a special security relationship to each other each ThreadGroup can also have child ThreadGroups, allowing for a ThreadGroup heirarchy

27 ThreadGroup class methods include:
int activeCount() & int activeGroupCount() int enumerate(Thread[] list, boolean recurse] ) int enumerate(ThreadGroup[] list, boolean recurse] ) int getMaxPriority() & void setMaxPriority() String getName() & ThreadGroup getParent() [set by constructor] boolean isDaemon() & void setDaemon(boolean daemon) list() [prints debugging info to System.out] interrupt()

28 ThreadGroups, continued
Threads can only modify each other (like setting their priorities) if they are in the same ThreadGroup By default, Threads go in the same ThreadGroup as the Thread that created it. To override this default behavior, pass a ThreadGroup to the Thread constructor. A Thread’s ThreadGroup cannot be changed.

29 Threads & Anonymous Inner Classes: FileWatcher Exercise
Complete the following class definition. Use an anonymous inner class that extends Thread. It should print a line to System.out when the file is created, or immediately if it already exists. You can not add code anywhere other than inside the watchFile method definition. import java.io.File; public class FileWatcher { public void watchFile( final String fileName ) { //fill this in, please. }

30 FileWatcher Solution t = new Thread() { File f = new File(fileName);
import java.io.File; public class FileWatcher { public void watchFile(final String fileName) { Thread t; t = new Thread() { File f = new File(fileName); public void run () { while (!f.exists()) { try { sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(fileName+" exists!"); }; t.start();

31 Threads & Anonymous Inner Classes: Timer Exercise
import java.util.*; public class Alarm { private static Timer timer = new Timer(); public static void stopAlarms() { timer.cancel(); } public static void setRecurringAlarm(final String msg, long interval) { /* Fill this in, please. After the interval specified by the parameter, the msg should be printed to System.out. After another interval, print the alarm msg again. Repeat... */ public static void main(String[] args) { Set up two alarms, one that prints “one second has passed” every second, and one that prints “five seconds have passed” every five seconds. Let them both go for twenty seconds, then stop them. After they have stopped, print “alarms stopped!”, and then the program should exit normally.

32 Timer Exercise Solution
import java.util.*; public class Alarm { private static Timer timer = new Timer(); public static void stopAlarms() { timer.cancel(); } public static void setRecurringAlarm(final String msg, long interval) { TimerTask task = new TimerTask() { public void run() { System.out.println(msg); }; timer.scheduleAtFixedRate(task, interval, interval); public static void main(String[] args) { long oneSecond = 1000, fiveSeconds = 5000, twentySeconds = 20000; Alarm.setRecurringAlarm("one second has passed", oneSecond); Alarm.setRecurringAlarm("five seconds have passed", fiveSeconds); Alarm.stopAlarms(); System.out.println("alarms stopped!"); timer.schedule(task, twentySeconds);


Download ppt "Advanced Java Class Threads."

Similar presentations


Ads by Google