Threads in Java. Processes and Threads Processes –A process has a self-contained execution...
-
Upload
allan-sherman -
Category
Documents
-
view
252 -
download
0
Transcript of Threads in Java. Processes and Threads Processes –A process has a self-contained execution...
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.
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
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.
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.
Thread Class Methods
Method MeaninggetName 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.
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 threadt.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");}}}
Single Thread: Example OutputCurrent thread: Thread[main,5,main]After name change: Thread[My Thread,5,main]54321
Runnable Object
• The Runnable interface defines a single method, run, meant to contain the code executed in the thread.
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(); } }
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
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
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
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.
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]); } }}
class NewThread implements Runnable {Thread t;NewThread() {// Create a new, second threadt = 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
class ThreadDemo {public static void main(String args[]) {new NewThread(); // create a new threadtry {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
Child thread: Thread[Demo Thread,5,main]Main Thread: 5Child Thread: 5Child Thread: 4Main Thread: 4Child Thread: 3Child Thread: 2Main Thread: 3Child Thread: 1Exiting child thread.Main Thread: 2Main Thread: 1Main thread exiting.
Example 2: Through Runnable InterfaceOutput
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.
Interrupt Status Flag
• Interrupt status flag• Invoking Thread.interrupt sets the flag
Method DescriptionisInterrupted() 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.
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
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
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
Exampleimport java.io.IOException;public class TryThread extends Thread {public TryThread(String firstName, String secondName, long delay) {this.firstName = firstName; // Store the first namethis.secondName = secondName; // Store the second nameaWhile = delay; // Store the delaysetDaemon(true); // Thread is daemon}public static void main(String[] args) {// Create three threadsThread 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");
Examplefirst.start(); // Start the first threadsecond.start(); // Start the second threadthird.start(); // Start the third threadtry {System.in.read(); // Wait until Enter key pressedSystem.out.println("Enter pressed...\n");} catch (IOException e) { // Handle IO exceptionSystem.out.println(e); // Output the exception}System.out.println("Ending main()");return;}// Method where thread execution will startpublic void run() {try {
Examplewhile(true) { // Loop indefinitely...System.out.print(firstName); // Output first namesleep(aWhile); // Wait aWhile msec.System.out.print(secondName + "\n"); // Output second name}} catch(InterruptedException e) { // Handle thread interruptionSystem.out.println(firstName + secondName + e); // Output the exception
}}private String firstName; // Store for first nameprivate String secondName; // Store for second nameprivate long aWhile; // Delay in milliseconds}
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(); // suspend the current thread until the thread1 dies
thread1.join(1000); // Wait up to 1 second for thread1 to diethread1.join(1000); // Wait up to 1 second for thread1 to die
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
t
Why to synchronize ?
i = i + 1;
(i = 31)
i = i + 1;
(i = 31)
starting value of i is 30starting value of i is 30
i = i - 1;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 3
0
30
i 29
29
Synchronized Methods
• Make methods mutually Exclusive.
• Using keyword Synchronized.
• Locking and Unlocking
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.
LAB TASK 1
1. Create a simple java program2. 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
Output
output: thread main step 0 thread main step 1 thread main step 2 thread main step 3 ... ……thread main step 99
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 Main4. Introduce the delay of “1 sec” for overlapping
execution of both threads.
Outputoutput: 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 ...