Created
February 16, 2019 09:09
-
-
Save jackblack369/aeee186128c28709e48ad12132d7a02a to your computer and use it in GitHub Desktop.
[code-thread] #java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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