How to use 'implements Runnable' in Java

By: Emiley J  

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.




Archived Comments

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

78. Threads can be implemented by extending Thread class, implementing Runnable interface and Callable i
View Tutorial          By: Ashish at 2014-07-25 08:44:08

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

80. I need to creat class. Write in class void named run(), then from starting midlet start class vith n
View Tutorial          By: Aliarth at 2012-11-18 00:03:15

81. Quite Helpful.....
^_^

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

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

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

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

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

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

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

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

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

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

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

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

93. new Thread(this , "Demo thread") mean

this is the thread object and Demo

View Tutorial          By: shalini at 2011-12-06 07:29:20

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

136. can you please explain this..!!

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

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

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


Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial