Presentation is loading. Please wait.

Presentation is loading. Please wait.

Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.

Similar presentations


Presentation on theme: "Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including."— Presentation transcript:

1 Threads in Java

2 Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including memory space. –Synonymous with program or application. –Most implementations of the Java virtual machine run as a single process.

3 Processes and Threads Threads –A thread is a flow of control –A thread is a series of executed statements –A thread is a nested sequence of method calls. –Threads exist within a process Every process has at least one. –Start execution with “Main Thread” but an application can be divided into many. –Concurrent programming

4 Multiple Threads

5 Creating Threads Program always has at least one thread: the one created when the program begins execution. In a normal Java application program, this thread starts at the beginning of main(). To start the execution of a thread, you call the start() method for the Thread object. The code that executes in a new thread is always a method called run(), which is public, accepts no arguments, and doesn’t return a value. Threads other than the main thread in a program always start in the run() method for the object that represents the thread.

6 Threads

7 Defining and Starting a Thread Create an object of java.lang.Thread class. Two ways. 1.One way is to define your class as a subclass of Thread and provide a definition of the method run(), which overrides the inherited method. 2.The other possibility is to define your class as implementing the interface Runnable, which declares the run() method, and then create a Thread object in your class when you need it.

8 Thread Class Methods Method Meaning getName Obtain a thread’s name. getPriority Obtain a thread’s priority. isAlive Determine if a thread is still running. join Wait for a thread to terminate. run Entry point for the thread. sleep Suspend a thread for a period of time. start Start a thread by calling its run method.

9 Single Thread: Example // Controlling the main Thread. class CurrentThreadDemo { public static void main(String args[]) { Thread t = Thread.currentThread(); System.out.println("Current thread: " + t); // change the name of the thread t.setName("My Thread"); System.out.println("After name change: " + t); try { for(int n = 5; n > 0; n--) { System.out.println(n); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted"); }}}

10 Single Thread: Example Output Current thread: Thread[main,5,main] After name change: Thread[My Thread,5,main] 5 4 3 2 1

11 Runnable Object The Runnable interface defines a single method, run, meant to contain the code executed in the thread.

12 Example 1: Through Runnable Interface public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new Thread(new HelloRunnable())).start(); }

13 public class HR implements Runnable { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { HR r=new HR(); Thread t=new Thread(r); t.start(); } } Example 1: Through Runnable Interface

14 SubClass Thread An application can subclass Thread, providing its own implementation of run.

15 public class HelloThread extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new HelloThread()).start(); } Example: Through Thread Class

16 public class HR extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { HR r=new HR(); r.start(); } } Example: Through Thread Class

17 Pausing Execution with Sleep Thread.sleep causes the current thread to suspend execution for a specified period. sleep(). –Takes time in milliseconds Interrupts can terminate the sleep period.

18 Example 1: Sleep Message public class SleepMessages { public static void main(String args[]) throws InterruptedException { String importantInfo[] = { "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too“ }; for (int i = 0; i < importantInfo.length; i++) { Thread.sleep(4000); System.out.println(importantInfo[i]); }

19 OUTPUT: Sleep Message

20 class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500);}} catch (InterruptedException e) { System.out.println("Child interrupted.");} System.out.println("Exiting child thread.");}} Example 2: Through Runnable Interface

21 class ThreadDemo { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); }} catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting.");}} Example 2: Through Runnable Interface

22 Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting. Example 2: Through Runnable Interface Output

23 Stopping Threads: Interrupt An interrupt is an indication to a thread that it should stop what it is doing and do something else. A thread sends an interrupt by invoking interrupt() on the Thread object.

24 Interrupt Status Flag Interrupt status flag Invoking Thread.interrupt sets the flag MethodDescription isInterrupted() Check if the thread's interrupt() method has been called (this does not clear the interrupted flag). isAlive() Tests if this thread is alive. A thread is alive if it has been started and has not yet died.

25 Daemon and User Threads The call to setDaemon(true), in the TryThread constructor makes the thread that is created a daemon thread A daemon thread: – Background thread that is subordinate to the thread that creates it. – When the thread that created the daemon thread ends, the daemon thread dies with it. –Threads that run indefinitely should usually defined as daemon threads

26 Daemon and User Threads A thread that is not a daemon thread is called a user thread : –Typically used for threads that run finite time –It must be explicitly stopped or destroyed, or its run method must return You can only call setDaemon() for a thread before it starts

27 Daemon and User Threads Main Thread thread1.setDaemon(true); thread1.start(); thread2.setDaemon(true); thread2.start(); thread3.start(); return; Main Thread thread1.setDaemon(true); thread1.start(); thread2.setDaemon(true); thread2.start(); thread3.start(); return; thread 1 created as a daemon thread thread 1 created as a daemon thread thread 2 created as a daemon thread thread 2 created as a daemon thread thread 3 created as a user thread thread 3 created as a user thread Ends the main thread. All daemon threads created in the main thread will end at this point Must be explicitly stopped or destroyed, or its run method must return

28 Example import java.io.IOException; public class TryThread extends Thread { public TryThread(String firstName, String secondName, long delay) { this.firstName = firstName; // Store the first name this.secondName = secondName; // Store the second name aWhile = delay; // Store the delay setDaemon(true); // Thread is daemon } public static void main(String[] args) { // Create three threads Thread first = new TryThread("Hopalong ", "Cassidy ", 200L); Thread second = new TryThread("Marilyn ", "Monroe ", 300L); Thread third = new TryThread("Slim ", "Pickens ", 500L); System.out.println("Press Enter when you have had enough...\n");

29 Example first.start(); // Start the first thread second.start(); // Start the second thread third.start(); // Start the third thread try { System.in.read(); // Wait until Enter key pressed System.out.println("Enter pressed...\n"); } catch (IOException e) { // Handle IO exception System.out.println(e); // Output the exception } System.out.println("Ending main()"); return; } // Method where thread execution will start public void run() { try {

30 Example while(true) { // Loop indefinitely... System.out.print(firstName); // Output first name sleep(aWhile); // Wait aWhile msec. System.out.print(secondName + "\n"); // Output second name } catch(InterruptedException e) { // Handle thread interruption System.out.println(firstName + secondName + e); // Output the exception } private String firstName; // Store for first name private String secondName; // Store for second name private long aWhile; // Delay in milliseconds }

31 Output

32 Connecting Threads Calling the join() method with no arguments will halt the current thread for as long as it takes the specified thread to die or with argument to specify the number of milliseconds to wait for the death of a thread thread1.join(); // suspend the current thread until the thread1 dies thread1.join(1000); // Wait up to 1 second for thread1 to die

33 Thread Scheduling

34 Synchronization The objective of synchronization is to ensure that when several threads want access to a single resource, only one thread can access it at any given time. Two ways to manage threads –manage code at the method level. –manage code at the block level

35 t Why to synchronize ? i = i + 1; (i = 31) i = i + 1; (i = 31) starting value of i is 30 i = i - 1; value of i is 31 ?? (it should be 30) value of i is 31 ?? (it should be 30) thread 2 thread 1 i 30 i 29

36 Synchronized Methods Make methods mutually Exclusive. Using keyword Synchronized. Locking and Unlocking

37 Example class MyClass { synchronized public void method1() { // Code for the method... } synchronized public void method2() { // Code for the method... } public void method3() { // Code for the method... } For the same object instance only one synchronized method can be executing at one time, because that method will have set the lock that prevents any other synchronized method from starting.

38 Example

39 LAB TASK 1 1.Create a simple java program 2.Having just one thread - the main thread. 3.Add a function which contains a loop that runs 10 times. 4.Display the name of the thread at each step with “1 sec” pause at each step. Note: Code Must handle Interrupted Exception

40 Output output: thread main step 0 thread main step 1 thread main step 2 thread main step 3... … thread main step 99

41 LAB TASK 2 1.Creating two parallel threads in “Main Thread” by implementing the Runnable interface 2.Add a "run" method. { write for loop which displays the names of threads} 3.Start both threads in Main 4.Introduce the delay of “1 sec” for overlapping execution of both threads.

42 Output output: thread Thread-0 step 0 thread Thread-1 step 0 thread Thread-0 step 1 thread Thread-1 step 1 thread Thread-0 step 2 thread Thread-1 step 2 thread Thread-0 step 3 thread Thread-1 step 3...

43 LAB TASK 3 Repeat “LAB TASK 2” by deriving our class from the "Thread" class.

44 Output output: thread Thread-0 step 0 thread Thread-1 step 0 thread Thread-0 step 1 thread Thread-1 step 1 thread Thread-0 step 2 thread Thread-1 step 2 thread Thread-0 step 3 thread Thread-1 step 3...


Download ppt "Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including."

Similar presentations


Ads by Google