How to use 'implements Runnable' in Java

By: Emiley J Viewed: 154685 times  Printer Friendly Format    


The easiest way to create a thread is to create a class that implements the Runnable interface. Runnable abstracts a unit of executable code. You can construct a thread on any object that implements Runnable. To implement Runnable, a class need only implement a single method called run( ), which is declared like this:

public void run( )

Inside run( ), you will define the code that constitutes the new thread. It is important to understand that run( ) can call other methods, use other classes, and declare variables, just like the main thread can. The only difference is that run( ) establishes the entry point for another, concurrent thread of execution within your program. This thread will end when run( ) returns.

After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread defines several constructors. The one that we will use is shown here:

Thread(Runnable threadOb, String threadName)

In this constructor, threadOb is an instance of a class that implements the Runnable interface. This defines where execution of the thread will begin. The name of the new thread is specified by threadName.

After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. In essence, start( ) executes a call to run( ). The start() method is shown here:

void start( )

Here is an example that creates a new thread using Runnable interface and starts it running:

// Create a second thread.
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.");
}
}

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.");
}
}

Inside NewThread's constructor, a new Thread object is created by the following statement:

t = new Thread(this, "Demo Thread");

Passing this as the first argument indicates that you want the new thread to call the run() method on this object. Next, start( ) is called, which starts the thread of execution beginning at the run( ) method. This causes the child thread's for loop to begin. After calling start( ), NewThread's constructor returns to main( ). When the main thread resumes, it enters its for loop. Both threads continue running, sharing the CPU, until their loops finish. The output produced by this program is as follows:

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.

As mentioned earlier, in a multithreaded program, the main thread must be the last thread to finish running. If the main thread finishes before a child thread has completed, then the Java run-time system may "hang." The preceding program ensures that the main thread finishes last, because the main thread sleeps for 1,000 milliseconds between iterations, but the child thread sleeps for only 500 milliseconds. This causes the child thread to terminate earlier than the main thread. Shortly, you will see a better way to ensure that the main thread finishes last.



Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. quite helpful
View Tutorial          By: kezyRoan at 2011-06-11 03:58:52

2. can you please explain this..!!

t =

View Tutorial          By: kalyan at 2011-06-30 00:01:10

3. errownSoymn
View Tutorial          By: errownSoymn at 2011-09-10 04:10:12

4. Picfilez
View Tutorial          By: Picfilez at 2011-09-14 10:27:38

5. oIcetAmere
View Tutorial          By: rIcetAmere at 2011-09-17 11:39:49

6. FlomaxUsa
View Tutorial          By: FlomaxUsa at 2011-09-19 18:28:38

7. zarazhenir
View Tutorial          By: zarazhenir at 2011-09-20 20:16:35

8. Siseasisonide
View Tutorial          By: Siseasisonide at 2011-09-21 09:03:26

9. Videosis
View Tutorial          By: Videosis at 2011-09-22 08:29:11

10. loofmeemi
View Tutorial          By: loofmeemi at 2011-09-27 21:54:27

11. edisteagoGdit
View Tutorial          By: edisteagoGdit at 2011-09-28 16:01:09

12. Reiffichewrix
View Tutorial          By: Reiffichewrix at 2011-09-29 17:39:21

13. scoursobe
View Tutorial          By: scoursobe at 2011-10-04 05:58:28

14. gadophyproria
View Tutorial          By: gadophyproria at 2011-10-04 07:00:19

15. netswodesty
View Tutorial          By: netswodesty at 2011-10-06 12:58:25

16. Glagsgooda
View Tutorial          By: Glagsgooda at 2011-10-06 20:11:59

17. Fleexyflild
View Tutorial          By: Fleexyflild at 2011-10-07 22:06:39

18. Steectmom
View Tutorial          By: Steectmom at 2011-10-09 05:52:12

19. scoursobe
View Tutorial          By: scoursobe at 2011-10-09 15:01:36

20. PlodeBefe
View Tutorial          By: PlodeBefe at 2011-10-10 07:36:38

21. Hildsaida
View Tutorial          By: Hildsaida at 2011-10-13 03:46:03

22. bratiiiika
View Tutorial          By: bratiiiika at 2011-10-13 23:36:29

23. webman
View Tutorial          By: webman at 2011-10-14 11:36:31

24. elenabukvp
View Tutorial          By: elenabukvp at 2011-10-15 08:44:01

25. Glagsgooda
View Tutorial          By: Glagsgooda at 2011-10-17 00:10:27

26. Dr.ChelopukJr
View Tutorial          By: Dr.ChelopukJr at 2011-10-24 23:41:09

27. Melatonin
View Tutorial          By: Melatonin at 2011-10-27 09:01:04

28. Steectmom
View Tutorial          By: Steectmom at 2011-10-30 20:55:49

29. FilippoviK
View Tutorial          By: FilippoviK at 2011-10-31 14:33:28

30. cithromaxer
View Tutorial          By: cithromaxer at 2011-10-31 17:15:34

31. Actiselotolek
View Tutorial          By: Actiselotolek at 2011-11-01 08:34:34

32. PHACelebrex
View Tutorial          By: PHACelebrex at 2011-11-02 18:12:04

33. Vilstwiff
View Tutorial          By: Vilstwiff at 2011-11-03 12:50:19

34. lorprense
View Tutorial          By: lorprense at 2011-11-04 06:43:28

35. DiopEloleanna
View Tutorial          By: DiopEloleanna at 2011-11-05 10:26:46

36. enivur
View Tutorial          By: enivur at 2011-11-16 07:45:20

37. merstenfertersak
View Tutorial          By: merstenfertersak at 2011-11-16 12:39:42

38. Booceethy
View Tutorial          By: Booceethy at 2011-11-22 18:27:00

39. colwfdq924
View Tutorial          By: zloaujr684 at 2011-11-24 07:32:24

40. onlinepharmacyidrugs
View Tutorial          By: onlinepharmacyidrugs at 2011-11-25 05:01:21

41. onlinepharmacyidrugs
View Tutorial          By: onlinepharmacyidrugs at 2011-11-25 05:25:34

42. onlinepharmacyidrugs
View Tutorial          By: onlinepharmacyidrugs at 2011-11-25 05:59:17

43. onlinepharmacyidrugs
View Tutorial          By: onlinepharmacyidrugs at 2011-11-25 06:23:20

44. onlinepharmacyidrugs
View Tutorial          By: onlinepharmacyidrugs at 2011-11-25 06:32:03

45. new Thread(this , "Demo thread") mean
View Tutorial          By: shalini at 2011-12-06 07:29:20

46. this is the thread object and thread name
View Tutorial          By: narain at 2011-12-06 07:33:07

47. Roxanew91
View Tutorial          By: Dariusu23 at 2011-12-14 19:38:04

48. ComprarViagraAR
View Tutorial          By: ComprarViagraAR at 2011-12-15 07:56:50

49. FordSoitSog
View Tutorial          By: FordSoitSog at 2011-12-15 21:00:46

50. Jeweler70
View Tutorial          By: Creonte70 at 2011-12-17 08:35:07

51. kromwel
View Tutorial          By: kromwel at 2011-12-19 08:19:22

52. BleargetBrend
View Tutorial          By: BleargetBrend at 2012-01-21 12:00:57

53. JescleleatKen
View Tutorial          By: JescleleatKen at 2012-02-02 17:34:03

54. nofReameRof
View Tutorial          By: nofReameRof at 2012-02-05 02:31:47

55. olrnfSkylx
View Tutorial          By: lolrrjSvkqhx at 2012-02-13 09:00:26

56. phharmmaccy
View Tutorial          By: phharmmaccy at 2012-02-25 10:22:00

57. Quite Helpful.....
^_^

View Tutorial          By: Alfred_Septio at 2012-09-26 12:38:47

58. I need to creat class. Write in class void named r
View Tutorial          By: Aliarth at 2012-11-18 00:03:15

59. Saved my life!
View Tutorial          By: Sahil Nair at 2013-09-21 09:26:54

60. Threads can be implemented by extending Thread cla
View Tutorial          By: Ashish at 2014-07-25 08:44:08

61. JasonGet
View Tutorial          By: JasonGet at 2017-01-26 22:50:33

62. VadivSt
View Tutorial          By: FizrukSt at 2017-01-30 16:08:30

63. lunetekopihab
View Tutorial          By: lunetekopihab at 2017-02-26 04:17:31

64. ecenepaq
View Tutorial          By: ecenepaq at 2017-02-26 04:56:24

65. upipudura
View Tutorial          By: upipudura at 2017-02-26 05:20:49

66. idiyekogipe
View Tutorial          By: idiyekogipe at 2017-02-26 05:35:25

67. iroxomoprid
View Tutorial          By: iroxomoprid at 2017-02-26 06:09:14

68. abivewokid
View Tutorial          By: abivewokid at 2017-02-26 06:26:35

69. uuqdoqul
View Tutorial          By: uuqdoqul at 2017-02-26 06:31:21

70. ofonojonar
View Tutorial          By: ofonojonar at 2017-02-26 06:57:39

71. egajihuyi
View Tutorial          By: egajihuyi at 2017-02-26 06:59:27

72. exofobejaziru
View Tutorial          By: exofobejaziru at 2017-02-26 08:13:25

73. ofifotu
View Tutorial          By: ofifotu at 2017-02-26 14:44:46

74. afacivuv
View Tutorial          By: afacivuv at 2017-04-10 05:28:23

75. etufohuwu
View Tutorial          By: etufohuwu at 2017-04-10 05:46:50

76. eqobhacun
View Tutorial          By: eqobhacun at 2017-04-10 06:02:06

77. aoegehahe
View Tutorial          By: aoegehahe at 2017-04-10 06:17:27

78. arizailufu
View Tutorial          By: arizailufu at 2017-04-10 06:21:21

79. mafayapuj
View Tutorial          By: mafayapuj at 2017-04-10 06:42:37

80. apixuyibe
View Tutorial          By: apixuyibe at 2017-04-10 06:43:47

81. albiape
View Tutorial          By: albiape at 2017-04-10 06:54:47

82. eliruso
View Tutorial          By: eliruso at 2017-04-10 07:02:14

83. ukoilono
View Tutorial          By: ukoilono at 2017-04-10 07:41:47

84. ofozototugayi
View Tutorial          By: ofozototugayi at 2017-04-10 08:28:03

85. ijhugif
View Tutorial          By: ijhugif at 2017-04-11 21:00:18

86. eyobulmu
View Tutorial          By: eyobulmu at 2017-04-12 06:07:11

87. edqizezebe
View Tutorial          By: edqizezebe at 2017-04-13 00:31:16

88. avujickebor
View Tutorial          By: avujickebor at 2017-04-13 10:38:03

89. ekereto
View Tutorial          By: ekereto at 2017-04-14 07:00:47

90. ulilirirox
View Tutorial          By: ulilirirox at 2017-04-14 18:23:06

91. eriyeufueq
View Tutorial          By: eriyeufueq at 2017-04-15 07:14:25

92. ofejelytitug
View Tutorial          By: ofejelytitug at 2017-04-15 19:23:29

93. oxesibilux
View Tutorial          By: oxesibilux at 2017-04-19 23:03:19

94. ixivoeqo
View Tutorial          By: ixivoeqo at 2017-06-05 08:26:23

95. ewrefufu
View Tutorial          By: ewrefufu at 2017-06-14 09:59:12

96. opekujictter
View Tutorial          By: opekujictter at 2017-06-14 10:45:24

97. orameni
View Tutorial          By: orameni at 2017-06-28 15:43:56

98. iasetacifupar
View Tutorial          By: iasetacifupar at 2017-06-28 16:12:37

99. ijejuqod
View Tutorial          By: ijejuqod at 2017-06-28 16:24:58

100. ipaxeavae
View Tutorial          By: ipaxeavae at 2017-07-13 21:54:38

101. icocexequxn
View Tutorial          By: icocexequxn at 2017-07-13 22:23:36

102. utaturesalboa
View Tutorial          By: utaturesalboa at 2017-07-13 22:32:47

103. esuniqna
View Tutorial          By: esuniqna at 2017-07-13 22:47:54

104. eyiociwa
View Tutorial          By: eyiociwa at 2017-07-16 23:52:29

105. unohihisume
View Tutorial          By: unohihisume at 2017-07-17 00:01:32

106. edidipezniza
View Tutorial          By: edidipezniza at 2017-07-17 00:09:00

107. hahisum
View Tutorial          By: hahisum at 2017-07-20 00:43:22

108. raxoupibe
View Tutorial          By: raxoupibe at 2017-07-20 00:57:10

109. ukucuzu
View Tutorial          By: ukucuzu at 2017-07-20 01:04:39

110. ovafofu
View Tutorial          By: ovafofu at 2017-07-20 01:33:11

111. ifilihoptyid
View Tutorial          By: ifilihoptyid at 2017-07-20 01:46:35

112. ifawesoaji
View Tutorial          By: ifawesoaji at 2017-07-23 00:12:35

113. uxecopi
View Tutorial          By: uxecopi at 2017-08-17 15:05:23

114. ijmgiuno
View Tutorial          By: ijmgiuno at 2017-08-30 02:31:37

115. okarovoze
View Tutorial          By: okarovoze at 2017-08-30 02:43:46

116. edixnate
View Tutorial          By: edixnate at 2017-08-30 02:44:17

117. ihipibexidu
View Tutorial          By: ihipibexidu at 2017-08-31 07:28:51

118. aaumiwxmel
View Tutorial          By: aaumiwxmel at 2017-08-31 08:02:11

119. oluconadod
View Tutorial          By: oluconadod at 2017-08-31 15:54:16

120. ucojutih
View Tutorial          By: ucojutih at 2017-08-31 16:07:25

121. aliueax
View Tutorial          By: aliueax at 2017-09-01 07:31:22

122. ucufiri
View Tutorial          By: ucufiri at 2017-09-01 07:31:50

123. uniroquedu
View Tutorial          By: uniroquedu at 2017-09-01 07:43:42

124. ufirajnbaka
View Tutorial          By: ufirajnbaka at 2017-09-01 08:05:32

125. ilnexeuzi
View Tutorial          By: ilnexeuzi at 2017-09-02 00:57:52

126. xusegzsahito
View Tutorial          By: xusegzsahito at 2017-09-08 19:30:51

127. eticasinaquir
View Tutorial          By: eticasinaquir at 2017-09-08 20:08:14

128. ojeavumu
View Tutorial          By: ojeavumu at 2017-09-08 20:40:09

129. educifanie
View Tutorial          By: educifanie at 2017-09-09 00:01:57

130. uroreyoi
View Tutorial          By: uroreyoi at 2017-09-09 19:53:41

131. ufgawiqapafe
View Tutorial          By: ufgawiqapafe at 2017-09-09 22:01:28

132. ogowenowo
View Tutorial          By: ogowenowo at 2017-09-09 23:24:36

133. ikejisooda
View Tutorial          By: ikejisooda at 2017-09-14 09:45:18

134. ufukomg
View Tutorial          By: ufukomg at 2017-09-14 09:59:30

135. ugitizaf
View Tutorial          By: ugitizaf at 2017-09-22 07:46:49

136. inofeqiu
View Tutorial          By: inofeqiu at 2017-09-22 07:58:59

137. icehuzol
View Tutorial          By: icehuzol at 2017-09-22 23:34:57