Lecture 6
Lecture 6
• What is multitasking ?
• Creating multitasking in Java
• Tasks synchronization
• Graphics animation
• Multimedia, sound
• Communication between server and many clients
What is Multitasking ?
• Approach
– Computer does some work on a task
– Computer then quickly switch to next task
– Tasks managed by operating system (scheduler)
• Computer seems to work on tasks concurrently
• Can improve performance by reducing waiting
Multitasking Can Aid Performance
• Single task
• Two tasks
Creating Threads in Java
• Two approaches
– Thread class
public class Thread extends Object { … }
– Runnable interface
public interface Runnable {
public void run(); // work thread
}
Thread Class
1. Thread class
– Extend Thread class and override the run method
• Example
public class MyT extends Thread {
public void run() {
… // work for thread
}
}
MyT t = new MyT () ; // create thread
t.start(); // begin running thread
… // thread executing in parallel
Creating Threads in Java
• Note
– Thread starts executing only if start() is called
– Runnable is interface
• So it can be multiply inherited
• Required for multithreading in frames
Threads – Thread States
try {
sleep((int)(Math.random() * 5000)); // 5 secs
} catch (InterruptedException e) { }
System.out.println(i);
}
• Possible outputs
– 0,1,2,0,1,2,Done // thread 1, thread 2, main()
– 0,1,2,Done,0,1,2 // thread 1, main(), thread 2
– Done,0,1,2,0,1,2 // main(), thread 1, thread 2
– 0,0,1,1,2,Done,2 // main() & threads interleaved
System.err.println( Thread.currentThread().getName() +
" setting sharedInt to " + val );
sharedInt = val;
writeable = false;
notify(); // tell a waiting thread to become ready
}