0% found this document useful (0 votes)
29 views

Lecture 6

The document discusses multitasking and threading in Java. It defines multitasking as running multiple tasks concurrently by quickly switching between them. It describes how threads allow multitasking in Java using either the Thread class or Runnable interface. Thread states like new, runnable, running, blocked, and dead are covered. Examples are provided to demonstrate creating and running threads concurrently in Java. Thread synchronization is also briefly discussed.

Uploaded by

ghazal.hpr5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Lecture 6

The document discusses multitasking and threading in Java. It defines multitasking as running multiple tasks concurrently by quickly switching between them. It describes how threads allow multitasking in Java using either the Thread class or Runnable interface. Thread states like new, runnable, running, blocked, and dead are covered. Examples are provided to demonstrate creating and running threads concurrently in Java. Thread synchronization is also briefly discussed.

Uploaded by

ghazal.hpr5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Multitasking

• ch.22 in Horstmann, 6th edition

• What is multitasking ?
• Creating multitasking in Java
• Tasks synchronization
• Graphics animation
• Multimedia, sound
• Communication between server and many clients
What is Multitasking ?

• Multiple tasks for computer


– Draw & display images on screen
– Check keyboard & mouse input
– Send & receive data on network
– Read & write files to disk
– Perform useful computation (editor, browser, game)
• How does computer do everything at once?
– Multitasking
– Multiprocessing
Multitasking (Time-Sharing)

• 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

public class Thread extends Object


implements Runnable {
public Thread();
public Thread(String name); // Thread name
public Thread(Runnable R);
public Thread(Runnable R, String name);

public void run();


public void start(); // begin thread execution
...
}
More Thread Class Methods

public class Thread extends Object {



public static Thread currentThread()
public String getName()
public void interrupt()
public boolean isAlive()
public void join()
public void setDaemon()
public void setName()
public void setPriority()
public static void sleep()
public static void yield()
}
Creating Threads in Java

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

• Java thread can be in one of these states


– New – thread allocated & waiting for start()
– Runnable – thread can begin execution
– Running – thread currently executing
– Blocked – thread waiting for event (I/O, etc.)
– Dead – thread finished
• Transitions between states caused by
– Invoking methods in class Thread
• new(), start(), yield(), sleep(), notify()…
– Other (external) events
• Scheduler, I/O, returning from run()…
Java Thread Example

public class ThreadExample extends Thread {


public void run() {

for (int i = 0; i < 3; i++)

try {
sleep((int)(Math.random() * 5000)); // 5 secs
} catch (InterruptedException e) { }
System.out.println(i);
}

public static void main(String[] args) {


ThreadExample t1;
t1 = new ThreadExample().start();
new ThreadExample().start();
System.out.println("Done");
}
}
Java Thread Example – Output

• 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

main (): thread 1, thread 2, println Done

thread 1: println 0, println 1, println 2

thread 2: println 0, println 1, println 2


Another Example
public class ThreadTester {
public static void main( String args[] ) {
PrintThread thread1, thread2, thread3, thread4; // display name and sleepTime
System.err.println( "Name: " + getName() +
"; sleep: " + sleepTime );
thread1 = new PrintThread( "thread1" ); }
thread2 = new PrintThread( "thread2" );
thread3 = new PrintThread( "thread3" ); public void run() {
// put thread to sleep for a random interval
thread4 = new PrintThread( "thread4" );
System.err.println( "\nStarting threads" ); try {
System.err.println( getName() + " going to sleep" );
// start executing PrintThreads Thread.sleep( sleepTime );
thread1.start(); }
// if thread interrupted during sleep, catch
thread2.start(); // exception and display error message
thread3.start();
thread4.start(); catch ( InterruptedException interruptedException ) {
System.err.println( "Threads started\n" ); System.err.println( interruptedException.toString() );
} }
} // end class ThreadTester // print thread name
System.err.println( getName() + " done sleeping" );
// Each object of this class picks a random }
sleep // interval. When a PrintThread executes, it
prints its // name, sleeps, prints its name again, } // end class PrintThread
terminates.

class PrintThread extends Thread {


private int sleepTime;
Note: System.err.println() is faster
public PrintThread( String name ) { than System.out.printn()
super( name );
// sleep between 0 and 5 seconds
sleepTime = (int) ( Math.random() * 5000 );
Thread Synchronization
• Thread synchronization can be done through the
monitors method and through the locks method.
• The synchronization of threads will be
demonstrated in a Produce/Consumer type
application.
• Such applications are used in the simulation of a
supermarket.
• In our program the Producer object creates the
integers: 1,2,…10 which are sent with method
setSharedInt() to a HoldInteger object and then
with the method getSharedInt() to the Consumer
object.
class HoldIntegerSynchronized
// class HoldIntegerSynchronized that uses thread synchronization
// to ensure that both threads access sharedInt at the proper times. public synchronized int getSharedInt()
// this is the monitors method {
while ( writeable ) { // not the consumer's turn
public class HoldIntegerSynchronized { try {
wait();
private int sharedInt = -1;
}
private boolean writeable = true; // condition variable catch ( InterruptedException e ) {
e.printStackTrace();
public synchronized void setSharedInt( int val ) }
{ }
while ( !writeable ) { // not the producer's turn
writeable = true;
try {
notify(); // tell a waiting thread to become ready
wait();
} System.err.println( Thread.currentThread().getName() +
catch ( InterruptedException e ) { " retrieving sharedInt value " + sharedInt );
e.printStackTrace(); return sharedInt;
} }
}
}

System.err.println( Thread.currentThread().getName() +
" setting sharedInt to " + val );
sharedInt = val;

writeable = false;
notify(); // tell a waiting thread to become ready
}

You might also like