C
C
Core Java
Search…
End Thread Execution

1) Using Boolean flag:

In this method, we declare one boolean variable called flag in a thread. Initially we set this flag as true. Keep the task to be performed in while loop inside the run() method by passing this flag. This will make thread continue to run until flag becomes false. We have defined stopRunning() method. This method will set the flag as false and stops the thread. Whenever you want to stop the thread, just call this method. Also notice that we have declared flag as volatile. This will make thread to read its value from the main memory, thus making sure that thread always gets its updated value.
1
class MyThread extends Thread
2
{
3
//Initially setting the flag as true
4
5
private volatile boolean flag = true;
6
7
//This method will set flag as false
8
9
public void stopRunning()
10
{
11
flag = false;
12
}
13
14
@Override
15
public void run()
16
{
17
//Keep the task in while loop
18
19
//This will make thread continue to run until flag becomes false
20
21
while (flag)
22
{
23
System.out.println("I am running....");
24
}
25
26
System.out.println("Stopped Running....");
27
}
28
}
29
30
public class MainClass
31
{
32
public static void main(String[] args)
33
{
34
MyThread thread = new MyThread();
35
36
thread.start();
37
38
try
39
{
40
Thread.sleep(100);
41
}
42
catch (InterruptedException e)
43
{
44
e.printStackTrace();
45
}
46
47
//call stopRunning() method whenever you want to stop a thread
48
49
thread.stopRunning();
50
}
51
}
Copied!
1
Output :
2
I am running….
3
I am running….
4
I am running….
5
I am running….
6
I am running….
7
I am running….
8
I am running….
9
Stopped Running….
Copied!

2) By calling interrupt() method

In this method, we use interrupt() method to stop a thread. Whenever you call interrupt() method on a thread, it sets the interrupted status of a thread. This status can be obtained by interrupted() method. This status is used in a while loop to stop a thread.
1
class MyThread extends Thread
2
{
3
@Override
4
public void run()
5
{
6
while (!Thread.interrupted())
7
{
8
System.out.println("I am running....");
9
}
10
11
System.out.println("Stopped Running.....");
12
}
13
}
14
15
public class MainClass
16
{
17
public static void main(String[] args)
18
{
19
MyThread thread = new MyThread();
20
21
thread.start();
22
23
try
24
{
25
Thread.sleep(100);
26
}
27
catch (InterruptedException e)
28
{
29
e.printStackTrace();
30
}
31
32
//interrupting the thread
33
34
thread.interrupt();
35
}
36
}
Copied!
1
Output :
2
I am running….
3
I am running….
4
I am running….
5
I am running….
6
I am running….
7
I am running….
8
I am running….
9
Stopped Running….
Copied!
Last modified 2yr ago