Presentation is loading. Please wait.

Presentation is loading. Please wait.

Software Engineering 3156 10-Oct-01 #11: All About Threads Phil Gross.

Similar presentations


Presentation on theme: "Software Engineering 3156 10-Oct-01 #11: All About Threads Phil Gross."— Presentation transcript:

1 Software Engineering 3156 10-Oct-01 #11: All About Threads Phil Gross

2 2 Administrivia HW2 Out Rose is up – No printing yet…

3 3 Threads Execution context Lightweight process Generally shares variables Allows your program to do multiple things at once Allows non-blocking I/O Always in use: – GC, AWT

4 4 Basics Two ways to create a Thread Subclass Thread and override run() Implement runnable, which means you have a public void run() method Thread t = new Thread(myRunnableObject); t.start(); Note: you don’t call run() directly!

5 5 Multithreaded Server KnockKnock examples

6 6 Thread Life Cycle Created, Runnable/not Runnable, Dead Here’s a state diagram:

7 7 Runnable / Not Runnable If a thread has been put to sleep, then the specified number of milliseconds must elapse. If a thread is waiting for a condition, then another object must notify the waiting thread of a change in condition by calling notify or notifyAll. If a thread is blocked on I/O, then the I/O must complete.

8 8 Synchronization Need a way to ensure that only one thread at a time is accessing an object Every Object in Java is potentially lockable When locked, any other thread that tries to access it will block While holding a lock, can safely reacquire the same lock (reentrant)

9 9 Synchronize Blocks Synchronized methods grab the lock on the associated object Syntactic sugar on generalized Synchronize blocks synchronize(foo) { … } Wait() or sleep() will release the lock until woken – Wait() is interrupt()able

10 10 Producer/Consumer Example Single shared variable

11 11 Timers Very handy One of the basic Unix system calls – getitimer/setitimer – Cleaned up considerably New with version 1.3 Java 1.2 has Swing-specific javax.swing.Timer

12 12 Timers Make Threads Run… At a specific time At a specific time and at fixed intervals thereafter After a delay After a delay and at fixed intervals thereafter

13 13 Two Periodic Schedules schedule(…) – Forces at least scheduled delay between runs scheduleAtFixedInterval(…) – Forces no more than maximum delay before last in sequence runs If first task takes too long… – schedule(…) will delay subsequent runs – sAFI(…) will run them as soon as possible to make up for the delay

14 14 Extras Thread priorities – Non preemptive on some platforms Thread grouping – Useful for Bots? Daemon threads – Don’t keep running for my sake…

15 15 Extras 2 Deadlock – Order your conditions Never stop/suspend/resume – Deprecated, unsafe Volatile – Assume variable could change at any time Stampede – Wake 100 threads at once…


Download ppt "Software Engineering 3156 10-Oct-01 #11: All About Threads Phil Gross."

Similar presentations


Ads by Google