Download Threads

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Threads
• What is a Thread?
• Multithreading
• Creating Threads – Subclassing java.lang.Thread
• Example 1
• Creating Threads – Implementing java.lang.Runnable
• Example 2
• Summary
• Exercises
Unit 14
1
What is a Thread?
•
•
•
A thread is a single sequential flow of control within a program.
At any given time during the runtime of the thread, there is a single point of
execution.
However, a thread itself is not a program; a thread cannot run on its own. Rather, it
runs within a program.
Unit 14
2
Multithreading
•
Multiple threads can be executed at
the same time within a single
program. Such usage is called multi
threading.
•
Each thread may perform a different
task in a single program
•
Multiple threads create an illusion of
several tasks being handled in
parallel. Actually the processor
allocates a fraction of its CPU cycle
time to execute each thread.
Unit 14
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 inputoutput)
– Sometimes advantageous to the programmer (such as simplifying program logic)
Unit 14
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.
Unit 14
5
Example 1
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
public class SimpleThread extends Thread {
private String title;
public SimpleThread(String str) {
this.title = str;
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + title);
try {
sleep((long)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
}
public static void main (String[] args) {
new SimpleThread("First Thread").start();
new SimpleThread("Second Thread").start();
}
}
Unit 14
6
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.
public static void main (String[] args) {
new SimpleThread("First Thread").start();
new SimpleThread("Second Thread").start();
}
Thread is created
and execution begins
………………..
………………
Control returns back to the next statement before completion of the current statement.
•
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.
Unit 14
7
Methods in java.lang.Thread – Contd.
•
The sleep() method (public static void sleep(long millis) throws
InterruptedException) makes the current thread inactive for a specified number of
milliseconds.
•
The InterruptedException is thrown when a thread is waiting, sleeping, or otherwise
paused for a long time and another thread interrupts it using the interrupt() method
in class Thread.
•
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
– More than one thread may have the same name
– If a name is not specified when a thread is created, a new name is generated.
Unit 14
8
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.
Unit 14
9
Example 2
1. import javax.swing.*;
2. public class TimeThread extends JFrame implements Runnable {
3.
4.
private JTextField sec, min, hrs;
5.
private JPanel panel;
6.
private int time = 0;
7.
8.
public TimeThread()
9.
{
10.
super(“Time");
11.
12.
sec = new JTextField(3); sec.setEditable(false); //makes textfield uneditable
13.
min = new JTextField(3); min.setEditable(false);
14.
hrs = new JTextField(3); hrs.setEditable(false);
15.
16.
panel = new JPanel();
17.
18.
panel.add(hrs); panel.add(min); panel.add(sec);
19.
20.
getContentPane().add(panel); pack(); setVisible(true);
21. }
Unit 14
10
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.}
Unit 14
11
Summary
•
A thread is a single sequential flow of control within a program.
•
The run() method of the Thread class and/or the Runnable interface contains the
code to be executed as a thread.
•
There are two ways to create a thread:
– Subclass the Thread class and override the run() method.
– Provide a class that implements the Runnable interface and therefore implements the
run() method.
•
One of the main advantages of implementing the Runnable interface is that when
our threaded application inherits from another class such as JFrame then we can
make it as a threaded application by implementing the Runnable interface.
Unit 14
12
Exercises
Q. 1 In the first example replace the statement new SimpleThread(“First
Thread”).start() with new SimpleThread(“First Thread”).run(). Observe the output
and explain why it happens. Does your program take longer time to complete?
Why?
Q. 2 Implement the TimeThread as a CountDown timer, for example, the timer counts 1
hour down to zero seconds. Include any action at the end of the time, such as
bringing up a JDialog informing that time is up.
Unit 14
13