Professional Documents
Culture Documents
Dokumen - Tips - Multithread MSC Lecture
Dokumen - Tips - Multithread MSC Lecture
Dokumen - Tips - Multithread MSC Lecture
Dep. of ISE
Application Building
Software Construction
2
Multithreading
• Multiple threads can be executed at
the same time within a single
program. Such usage is called multi
threading.
3
Introduction: Where are Threads Used?
• Threads are used by virtually every computer user in the following instances:
– In Internet browsers
– In databases
– In operating systems (for controlling access to shared resources etc)
• Benefits of threads
– More productivity to the end user (such as responsive user interface)
– More efficient use of the computer (such as using the CPU while performing input-
output)
– Sometimes advantageous to the programmer (such as simplifying program logic)
4
Creating Java Threads – Subclassing java.lang.Thread
• There are two ways to create threads in java. Assume you have a class “MyClass”
which may contain several tasks to be executed as threads. One of the ways to
create and execute a threaded application is as follows:
– “MyClass” should be declared to be a subclass of java.lang.Thread.
– “MyClass” should override the run method (public void run()) of class Thread.
– An instance of the “MyClass” can then be instantiated and executed as a thread
using the start() method.
– Note that the code to be executed as thread should be in the run() method of
“MyClass”.
– The following example shows how this can be done.
5
Asst.Prof.Dr.Raghad 6
Z.Yousif
Asst.Prof.Dr.Raghad 7
Z.Yousif
Asst.Prof.Dr.Raghad 8
Z.Yousif
Asst.Prof.Dr.Raghad 9
Z.Yousif
Asst.Prof.Dr.Raghad 10
Z.Yousif
11
Asst.Prof.Dr.Raghad Z.Yousif
Asst.Prof.Dr.Raghad 12
Z.Yousif
Asst.Prof.Dr.Raghad 13
Z.Yousif
Example 1
14
Methods in java.lang.Thread
• The run() method contains the code which has to be executed as threads.
• The start() method is the method invoked in order for the threads to run in a
multithreaded way.
• As soon as a call to start() is made, the thread is created and starts execution.
Control returns back immediately to the next statement in the program while the
thread may be in execution.
• Note that if a call new SimpleThread.run() is made, the run() method is executed in the current
thread and the new thread is never started.
15
Methods in java.lang.Thread – Contd.
• The getName() (public final String getName()) method returns back the name of the
current thread as a String.
• Every thread has a name (including anonymous threads) for identification purposes
16
Creating Java Threads – Implementing java.lang.Runnable
• Another way to create and execute Java threads is as follows. Assume you have a
class “MyClass” which may contain several tasks to be executed as threads.
– “MyClass” should implement the interface java.lang.Runnable
– “MyClass” should implement the run method (public void run()) of the
interface Runnable
– An instance of the Thread class can be created using an instance of “MyClass”
as a parameter as follows:
Thread t = new Thread(new MyClass());
– Now the run() method of “MyClass” can be executed as a thread by invoking
the start() method using t.start().
– Note that the code to be executed as thread should be in the run() method of
MyClass.
– The following example shows how this can be done.
17
Example 2
1. import javax.swing.*;
18
Example – Contd.
22. public void run()
23. {
24. try {
25. while(true) {
26. Thread.sleep(1000); time++;
27. sec.setText(time%60 + ""); //Display seconds
28. min.setText((time – (time/3600)*3600)/60 + ""); //Display minutes
29. hrs.setText(time/3600 + ""); //Display hours
30. }
31. } catch(InterruptedException e) {}
32. }
33.
34. public static void main(String[] args)
35. {
36. TimeThread t = new TimeThread();
37. Thread mytime = new Thread(t);
38. mytime.start();
39. }
40.}
19
Thread Priority
• Execution of multiple threads on a single CPU in some order is called scheduling.
• At any given time, when multiple threads are ready to be executed, the runtime
system chooses for execution the Runnable thread that has the highest priority.
• If two threads of the same priority are waiting for the CPU, the scheduler arbitrarily
chooses one of them to run.
20
Thread Priority
public static final int MIN_PRIORITY 1
public static final int NORM_PRIORITY 5
• The methods int getPriority() and setPriority(int priority) are used the accessor and
mutator methods used for the priority of a Java thread.
21
Thread Priority – Example 1
1. public class SimplePThread extends Thread {
2.
3. public SimplePThread(String str) {
4. super(str); //Thread can be created using a string
5. }
6. public void run() {
7. for (int i = 1; i < 400; i++) {
8. for(int j = 0; j < 40000; j++)
9. System.out.print(""); //Keeps thread busy
10. System.out.print(getName());
11. }
12. System.out.print(".");
13. }
14. public static void main (String[] args) {
15.
16. Thread t1 = new SimplePThread("1");
17. Thread t2 = new SimplePThread("2");
18.
19. t1.setPriority(Thread.NORM_PRIORITY + 1);
20. t2.setPriority(Thread.NORM_PRIORITY - 1);
21.
22. System.out.println("Thread 1 has priority " + t1.getPriority());
23. System.out.println("Thread 2 has priority " + t2.getPriority());
24.
25. t1.start(); t2.start();
26. }
27. }
22
Asst.Prof.Dr.Raghad 23
Z.Yousif
Asst.Prof.Dr.Raghad 24
Z.Yousif
Asst.Prof.Dr.Raghad 25
Z.Yousif
Asst.Prof.Dr.Raghad 26
Z.Yousif
Asst.Prof.Dr.Raghad 27
Z.Yousif
Asst.Prof.Dr.Raghad 28
Z.Yousif
Asst.Prof.Dr.Raghad 29
Z.Yousif
The interrupt() method
• The interrupt() method (public void interrupt()) interrupts the current thread. If thread is
inactive, an InterruptedException is thrown which must be caught.
• The isInterrupted() method (public boolean isInterrupted()) checks if the current thread
is interrupted or not.
30
Example 2
1. import javax.swing.*;
2. import java.awt.event.*;
31
Example 2 – Contd.
32
Example 2 – Contd.
33
Thread Synchronization
• When two or more threads access a shared resource, (for example a variable), the resource may be
corrupted e.g., unsynchronized threads accessing the same database
• Such blocks of code are usually called critical sections and must be executed in a mutually-
exclusive way
• When a block of Java code guarded by the synchronized keyword, it can be executed by only
one thread at any time
• You can synchronize an entire method or just a few lines of code by using the synchronized
keyword
• Note that code that is thread-safe (i.e, guarded by synchronized) is slower than code that is
not.
• Next, we present an example which shows problems due to shared thread access and then the
synchronized thread version.
34
Example 2
class BankAccount public class UnsafeBankAccount extends Thread{
{ private int balance; BankAccount ba;
public BankAccount(int balance) public UnsafeBankAccount(BankAccount ba)
{ this.balance = balance; } { this.ba = ba; }
int get()
{ return balance; }
} 35
Thread Synchronization
• When the program is executed, it may produce
erroneous output.
36
Thread Synchronization
• One solution to the problem pointed out is to use the synchronized keyword with all
methods that deal with the variable balance.
• This is to ensure that only one thread accesses the variable balance at a time.
• Other threads may wait() while one thread is accessing and modifying the variable balance.
The method wait() is inherited by the class java.lang.Thread from the class java.lang.Object.
• When the thread accessing and modifying the variable balance is done, it may
notifyAll() threads waiting to execute the synchronized methods.
37
Example 3
class MyBankAccount public class SafeBankAccount extends Thread{
{ private int balance; MyBankAccount ba;
private boolean busy = false;
public SafeBankAccount(MyBankAccount ba)
public MyBankAccount(int balance) { this.ba = ba; }
{ this.balance = balance; }
public void run()
public void doNothing() {
{ depositWithdraw(10); depositWithdraw(20); System.out.println(getName()+" got initial balance: "+
depositWithdraw(30); ba.get());
} ba.doNothing();
System.out.println(getName()+" got final balance: "+
public synchronized void depositWithdraw(int ba.get());
money)
{ try }
{ while(busy) wait();
busy = true; balance += money; public static void main(String[] args ){
Thread.sleep((long)(Math.random()*1000)); MyBankAccount ba = new MyBankAccount(0);
balance -= money; busy = false; for(int i=0; i < 9; i++)
notifyAll(); //notifies all waiting threads new SafeBankAccount(ba).start();
} catch(InterruptedException e){} }
} }
• The run() method increments the y coordinate of the ball to be drawn. If the y-
coordinate exceeds the height of the window, the ball is reflected back by negating
the increment.
39
Example 4 – Thread Animations
import java.awt.*; public void run(){
import java.applet.Applet; int yDir = +1;
int incr = 10;
public class UpDown extends Applet implements int sleepFor = 50;
Runnable {
int radius, x, y; while(true) {
Thread t; y += (incr * yDir);
repaint();
public void init() {
radius = 20; if(y - radius < incr ||
x = 30; //signifies x location y + radius + incr > getSize().height)
y = 20; //signifies y location yDir *= -1; //reflect the ball back
Thread t = new Thread(this);
t.start(); try{
} t.sleep(sleepFor);
}catch(InterruptedException e) {}
public void paint(Graphics g) { } // end while
g.setColor(Color.blue); }
g.fillOval(x - radius, y - radius, 2*radius, }
2*radius);
}
40