Top Banner
Creating Threads using Runnable interface 1
27
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Runnable interface.34

Creating Threads using Runnable interface

1

Page 2: Runnable interface.34

On completion of this period, you would be able to learn• Creating threads using Runnable interface• Creating multiple threads

2

Objectives

Page 3: Runnable interface.34

Recap

3

In the previous class we learnt that there are two

ways to create a thread

1. Extending Thread class

2. Implementing Runnable interface

• We have created threads using Thread class

Page 4: Runnable interface.34

Implementing Runnable Interface

4

• The Runnable interface has only one method

• run() method

• The Runnable interface should be implemented by

• Any class whose instances are intended to be

executed as a thread

• The class must define run() method of no arguments

• The run() method is like main() for the new thread

• A class that implements Runnable can run by

• Instantiating a Thread instance and passing itself in

as the target

Page 5: Runnable interface.34

Implementing Runnable Interface contd..

5

• Two Ways of Starting a Thread For a class that implements Runnable

• The first approach:• Caller thread creates Thread object and starts

it explicitly after an object instance of the class that implements Runnable interface is created• The start() method of the Thread object

needs to be explicitly invoked after object instance is created

Page 6: Runnable interface.34

Implementing Runnable Interface contd..

6

• The second approach• The Thread object is created and started

within the constructor method of the class that implements Runnable interface• The caller thread just needs to create

object instances of the Runnable class

Page 7: Runnable interface.34

Scheme 1: Explicit start

7

class PrintNameRunnable implements Runnable {

String name;

PrintNameRunnable(String name) {

this.name = name;

}

public void run() {

for (int i = 0; i < 10; i++) {

System.out.print(name);

}

}

}

Page 8: Runnable interface.34

Scheme 1: Explicit start

8

Public class RunnableThreadTest1 {

public static void main(String args[]) {

PrintNameRunnable pnt1 = new PrintNameRunnable("A");

Thread t1 = new Thread(pnt1);

t1.start();

}

}

Page 9: Runnable interface.34

Scheme 2: Started in constructor

9

Class PrintNameRunnable implements Runnable {

Thread thread;

PrintNameRunnable(String name) {

thread = new Thread(this, name);

thread.start();

}

public void run() {

String name = thread.getName();

for (int i = 0; i < 10; i++) {

System.out.print(name);

}

}

}

Page 10: Runnable interface.34

Scheme 2: Started in constructor contd..

10

public class RunnableThreadTest2 {

public static void main (String args []) {

new Print Name Runnable ("A");

new Print Name Runnable ("B");

new Print Name Runnable ("C");

}

}

Page 11: Runnable interface.34

Thread vs. Runnable

11

• Choosing between these two is a matter of taste• Implementing the Runnable interface

• May take more work since we still • Declare a Thread object• Call the Thread methods on this object

• Your class can still extend other class• Extending the Thread class

• Easier to implement• Your class can no longer extend any other class

Page 12: Runnable interface.34

Example Program

12

class NewThread implements Runnable {

String name; // name of thread

Thread t;

NewThread(String threadname) {

name = threadname;

t = new Thread(this, name);

System.out.println("New thread: " + t);

t.start(); // Start the thread

}

Giving a name to the thread

Scheme 2 is used

Page 13: Runnable interface.34

Example Program contd..

13

// This is the entry point for thread.

public void run() {

try {

for (int i = 5; i > 0; i--) {

System. out. println (name + ": " + i);

Thread.sleep(1000);

}

} catch (Interrupted Exception e) {

System. out. Println ( name + "Interrupted");

}

System. out. Println (name + " exiting.");

}

}

Page 14: Runnable interface.34

Example Program contd..

14

class RunnableThread {

public static void main(String args[]) {

new NewThread("Child Thread"); // create a new thread

try {

for(int i = 5; i > 0; i--) {

System.out.println("Main Thread: " + i);

Thread.sleep(500);

}

} catch (InterruptedException e) {

System.out.println("Main thread interrupted.");

}

System.out.println("Main thread exiting.");

}

}

Page 15: Runnable interface.34

Example Program

15

Output

main thread finishes first

Page 16: Runnable interface.34

Example Program

16

class PrintThread extends Thread {

private int sleepTime;

// PrintThread constructor assigns name to thread

// by calling Thread constructor

public PrintThread( String name )

{

super( name );

// sleep between 0 and 5 seconds

sleepTime = (int) ( Math.random() * 5000 );

System.out.println( "Name: " + getName() +

"; sleep: " + sleepTime );

}

Generate a random number within 5000

Page 17: Runnable interface.34

Example Program contd..

17

public void run() { // put thread to sleep for a random interval try { System.out.println( getName() + " I have done my work" ); System.out.println( getName() + " going to sleep" ); Thread.sleep( sleepTime ); } catch ( InterruptedException exception ) { System.out.println( exception.toString() ); } System.out.println( getName() + " done sleeping" ); }}

Page 18: Runnable interface.34

Example Program contd..

18

public class ThreadTester {

public static void main( String args[] )

{

PrintThread thread1, thread2, thread3, thread4;

thread1 = new PrintThread( "thread1" );

thread2 = new PrintThread( "thread2" );

thread3 = new PrintThread( "thread3" );

thread4 = new PrintThread( "thread4" );

System.out.println( "\nStarting threads" );

Page 19: Runnable interface.34

Example Program contd…

19

thread1.start();

thread2.start();

thread3.start();

thread4.start();

System. out. Println ( "Threads started\n" );

}

}

Page 20: Runnable interface.34

Example Program Contd..

20

Output

Page 21: Runnable interface.34

Summary

• In this class you have learnt • The second way of creating threads i.e., by

implementing Runnable interface• The two schemes for the above approach• Creating multiple threads

21

Page 22: Runnable interface.34

Frequently Asked Questions

1. List the steps for creating the thread by implementing Runnable interface

2. Explain the need for multithreading

3. Explain the steps needed to create multiple threads and using them

22

Page 23: Runnable interface.34

Quiz

1.How many methods are there in Runnable interface ?1. One

2. Two

3. Three

4. More than three

23

Page 24: Runnable interface.34

Quiz Contd..

2.What is the name of the method in Runnable interface ?

1. runnable ()

2. run ()

3. running ()

4. runs ()

Page 25: Runnable interface.34

Quiz Contd..3.When you create a thread object in main method and run it,

how many threads do you expect running in parallel ?

1. One

2. Two

3. Three

4. More than three

25

Page 26: Runnable interface.34

Quiz Contd..

4.When we implement the Runnable interface, we must define the method

1. start()

2. stop()

3. run()

4. main()

Page 27: Runnable interface.34

Assignments

• Write a Java thread that prints even numbers up to 20

• Write a Java thread that prints odd numbers up to 20

• Write a Java thread that prints prime numbers up to 100• In all the above programs, put the delay of one

second after every print• Write a Java program to create multiple threads

using the above three threads

27