Presentation is loading. Please wait.

Presentation is loading. Please wait.

Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.

Similar presentations


Presentation on theme: "Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable."— Presentation transcript:

1 Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable Example 2 Summary Exercises

2 Unit 142 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.

3 Unit 143 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.

4 Unit 144 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)

5 Unit 145 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.

6 Unit 146 Example 1 1.public class SimpleThread extends Thread { 2. private String title; 3. public SimpleThread(String str) { 4. this.title = str; 5. } 6. 7. public void run() { 8. for (int i = 0; i < 10; i++) { 9. System.out.println(i + " " + title); 10. try { 11. sleep((long)(Math.random() * 1000)); 12. } catch (InterruptedException e) {} 13. } 14. System.out.println("DONE! " + getName()); 15. } 16. 17. public static void main (String[] args) { 18. new SimpleThread("First Thread").start(); 19. new SimpleThread("Second Thread").start(); 20. } 21.}

7 Unit 147 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. 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.

8 Unit 148 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.

9 Unit 149 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.

10 Unit 1410 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. }

11 Unit 1411 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.}

12 Unit 1412 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.

13 Unit 1413 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.


Download ppt "Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable."

Similar presentations


Ads by Google