Skip to content

Instantly share code, notes, and snippets.

@jackblack369
Created February 16, 2019 09:09
Show Gist options
  • Save jackblack369/aeee186128c28709e48ad12132d7a02a to your computer and use it in GitHub Desktop.
Save jackblack369/aeee186128c28709e48ad12132d7a02a to your computer and use it in GitHub Desktop.
[code-thread] #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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment