350 likes | 549 Views
Web programming Winter 2006. What are threads?. A thread in computer science is short for a thread of execution or a sequence of instructions. Multiple threads can be executed in parallel on many computer systems. This multithreading generally occurs by time slicing (where a single processor switc
E N D
1. Web programming Winter 2006 Java Threads 1 Web Programming course
Dan Goldwasser
dgoldwas@cs.haifa.ac.il
2. Web programming Winter 2006 What are threads? A thread in computer science is short for a thread of execution or a sequence of instructions. Multiple threads can be executed in parallel on many computer systems.
This multithreading generally occurs by time slicing (where a single processor switches between different threads) or by multiprocessing (where threads are executed on separate processors).
Threads are similar to processes, but differ in the way that they share resources.
(From Wikipedia, the free encyclopedia)
3. Web programming Winter 2006 Thread operation
4. Web programming Winter 2006 Some Buzz words… Multithreading vs. Multitasking
Concurrency vs. parallelism
5. Web programming Winter 2006 What is good for? Maintain responsiveness of an application during a long running task
Enable cancellation of separable tasks
Some problems are intrinsically parallel
To monitor status of some resource (DB)
Some APIs and systems demand it: Swing
To take advantage of multiple processors
6. Web programming Winter 2006 Java implementation of threads We shall look at three version of thread instances
Interface Runnable
Class TimerTask
Class Thread
7. Web programming Winter 2006 java.lang.Runnable An adapter which enables any given class to operate as a thread
Requires one method be implemented:
public void run()
Most common method for adding threads to an application
8. Web programming Winter 2006 Example 1 class Counter implements Runnable {
private int maxNumber;
public Counter(int max){
maxNumber=max;
}
public void run(){
int i=0
while(i<maxNumber)
i++; }
…
9. Web programming Winter 2006 Timer and TimerTask A simple way to use threads is to schedule a timer and let the thread work periodically
Class Timer
Class TimerTask
10. Web programming Winter 2006 class TimerTask A task that can be scheduled for one-time or repeated execution by a Timer.
11. Web programming Winter 2006 class Timer facility for threads to schedule tasks for future execution in a background thread.
12. Web programming Winter 2006 Example 2 public class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(),seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
cancel(); //Terminate the timer thread
}
}
public static void main(String args[]) {
new Reminder(5);
}
}
13. Web programming Winter 2006 class Thread A base class with maximum threading functionality.
While less common, it is far more powerful.
Forces the focus of your class to its “threadedness”.
Minimum requirements are like Runnable:
public void run()
14. Web programming Winter 2006 class Thread
15. Web programming Winter 2006 Example 3 public class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
System.out.println("DONE! " + getName());
}
…
public static void main (String[] args) {
new SimpleThread("Jamaica").start();
new SimpleThread("Fiji").start(); }
}
16. Web programming Winter 2006 What is the output of this code?
17. Web programming Winter 2006
18. Web programming Winter 2006 Example 4 class Counter implements Runnable {
private int maxNumber;
public Counter(int max){
maxNumber=max;
}
public void run(){
int i=0
while(i++<maxNumber)
}
}
public static void main(String[] args){
runnable r=new Counter(5);
Thread t = new Thread(r);
t.start();
}
19. Web programming Winter 2006 Thread life cycle
20. Web programming Winter 2006 Thread states A thread is not runnable if –
Its sleep method is invoked
The thread calls the wait method to wait for a specific condition to be satisfied
The thread is blocking on I/O
A thread will be runnable again when-
If a thread has been put to sleep, 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, the I/O must complete
21. Web programming Winter 2006 Interrupting a thread If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.
If none of the previous conditions hold then this thread's interrupt status will be set
22. Web programming Winter 2006 Interrupting a thread The program creates two threads and interrupts them
23. Web programming Winter 2006 class Counter extends Thread {
public void run ( ) {
long count = 0 ;
while (true) {
if(Thread.interrupted ( ) ) {
System.out.println (“Counter was interrupted”) ;
System.out.println (“count = “ + count) ;
break ;
}
++count ;
}
}
}
class Sleeper extends Thread {
public void run ( ) {
try {
Thread.sleep (5000) ;
} catch (InterruptedException e) {
System.out.println (“Sleeper was interrupted”) ;
}
}
}
24. Web programming Winter 2006 Thread Identification The identity of the currently running thread can be found using the currentThread method
This has a static modifier, which means that there is only one method for all instances of Thread objects
The method can always be called using the Thread class
25. Web programming Winter 2006 Thread Scheduling Execution of multiple threads on a single CPU in some order is called scheduling
The JRE supports a very simple, deterministic scheduling algorithm called fixed-priority scheduling.
schedules threads on the basis of their priority relative to other Runnable threads.
The thread scheduling algorithm is also preemptive. If at any time a thread with a higher priority than all other Runnable threads becomes Runnable, system chooses the new higher-priority thread for execution.
The new thread is said to preempt the other threads
26. Web programming Winter 2006 Thread priorities and scheduling Every thread has a priority which can be increased or decreased by calling the setPriority() method
Thread.MIN_PRIORITY is the minimum priority (defined 1)
Thread.MAX_PRIORITY is the maximum priority (defined as 10)
When a thread is created, it is given a priority of 5 – defined as Thread.NORM_PRIORITY
27. Web programming Winter 2006 Time slicing Time slicing comes into play when multiple Runnable threads of equal priority are the highest-priority threads competing for the CPU
The Java platform does not implement time slicing. However, some platforms do support time slicing. Your programs should not rely on time slicing, as it may produce different results on different systems
A thread can voluntarily yield the CPU by calling the yield method. The yield method gives other threads of the same priority a chance to run. If no equal-priority threads are Runnable, the yield is ignored.
28. Web programming Winter 2006 Thread scheduling Differs depending on the operating system
Windows NT
Each thread is given a time slice after which it is pre-empted by another thread of higher or equal priority
Solaris (UNIX)
A thread can only be pre-empted by a thread of higher priority. If one is not available, the thread runs to completion
In both cases, lower priority threads can only run if all higher priority threads are blocked
29. Web programming Winter 2006 What is the output of this code?
30. Web programming Winter 2006 Hmmm… Scheduling multithreaded programs introduces some new concepts
non-determinism
race condition
concurrency
A mechanism for synchronizing the threads could be useful.. (next session)
31. Web programming Winter 2006 Summary What are threads? What are they good for?
How are threads implemented in Java?
In what states could a thread be? How does a thread move between states?
How is the threads execution order determined?
What are the risks of using threads?
32. Web programming Winter 2006 Questions?
33. Web programming Winter 2006 Example 3 public class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
System.out.println("DONE! " + getName());
}
…
public static void main (String[] args) {
new SimpleThread("Jamaica").start();
new SimpleThread("Fiji").start(); }
}