# 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.

```java
class MyThread extends Thread
{
	//Initially setting the flag as true
	
	private volatile boolean flag = true;
	
	//This method will set flag as false
	
	public void stopRunning()
	{
		flag = false;
	}
	
	@Override
	public void run()
	{
		//Keep the task in while loop
		
		//This will make thread continue to run until flag becomes false
		
		while (flag)
		{
			System.out.println("I am running....");
		}
		
		System.out.println("Stopped Running....");
	}
}

public class MainClass 
{   
	public static void main(String[] args) 
	{
		MyThread thread = new MyThread();
		
		thread.start();
		
		try 
		{
			Thread.sleep(100);
		} 
		catch (InterruptedException e) 
		{
			e.printStackTrace();
		}
		
		//call stopRunning() method whenever you want to stop a thread
		
		thread.stopRunning();
	}	
}
```

```
Output :
I am running….
I am running….
I am running….
I am running….
I am running….
I am running….
I am running….
Stopped Running….
```

### 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.

```java
class MyThread extends Thread
{	
	@Override
	public void run()
	{
		while (!Thread.interrupted())
		{
			System.out.println("I am running....");
		}
		
		System.out.println("Stopped Running.....");
	}
}

public class MainClass 
{   
	public static void main(String[] args) 
	{
		MyThread thread = new MyThread();
		
		thread.start();
		
		try 
		{
			Thread.sleep(100);
		} 
		catch (InterruptedException e) 
		{
			e.printStackTrace();
		}
		
		//interrupting the thread
		
		thread.interrupt();
	}	
}
```

```
Output :
I am running….
I am running….
I am running….
I am running….
I am running….
I am running….
I am running….
Stopped Running….
```

